Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
Getting the error of a Powershell Script within c# and outputting it with conditional statement?

I have a console application and a method that executes a PowerShell script within the console application. So I'm trying to grab an error text that it outputs in the application and do something with it.

Example/What I'm trying to do:

    If Error.contains("Object") 
{
    // do something here
}

Here is my current method

  public void ExecutePowershellScript()
{
  var file = @"C:\Path\filename.ps1";
           
            var start = new ProcessStartInfo()
            {
                FileName = "powershell.exe",
                Arguments = $"-NoProfile -ExecutionPolicy unrestricted -file \"{file}\"",
                UseShellExecute = false
            };
            Process.Start(start);
}
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Process.start: how to get the output?

When you create your Process object set StartInfo appropriately:

var proc = new Process 
{
    StartInfo = new ProcessStartInfo
    {
        FileName = "program.exe",
        Arguments = "command line arguments to your executable",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    }
};

then start the process and read from it:

proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
    string line = proc.StandardOutput.ReadLine();
    // do something with line
}

You can use int.Parse() or int.TryParse() to convert the strings to numeric values. You may have to do some string manipulation first if there are invalid numeric characters in the strings you read.

over 4 years ago · Santiago Trujillo Report

0

You can set RedirectStandardError = true and access any errors from process.StandardError

    public static void ExecutePowershellScript()
    {
        var file = @"C:\Path\filename.ps1";

        var start = new ProcessStartInfo()
        {
            FileName = "powershell.exe",
            Arguments = $"-NoProfile -ExecutionPolicy unrestricted -file \"{file}\"",
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true
        };
        using Process process = Process.Start(start);
        string output = process.StandardOutput.ReadToEnd();
        string errors = process.StandardError.ReadToEnd();
    }



Okay, scratch the above suggestion. After being corrected by mklement0,

This is a perfectly reasonable attempt, but, unfortunately, it can lead to hangs (while waiting for one's stream end, the other, when exceeding the buffer size, may cause process execution to block). If you need to capture both streams, you must collect the output from one of them via events. – mklement0

I changed the solution to use the ErrorDataReceived event

        public static async Task ExecutePowershellScript()
        {
            var file = @"C:\Path\filename.ps1";

            var start = new ProcessStartInfo
            {
                FileName = "powershell.exe",
                Arguments = $"-NoProfile -ExecutionPolicy unrestricted -file \"{file}\"",
                UseShellExecute = false,
                // redirect standard error stream to process.StandardError
                RedirectStandardError = true
            };

            using var process = new Process
            {
                StartInfo = start
            };

            // Subscribe to ErrorDataReceived event
            process.ErrorDataReceived += (sender, e) =>
            {
                //  code to process the error lines in e.Data
            };

            process.Start();

            // Necessary to start redirecting errors to StandardError
            process.BeginErrorReadLine();

            // Wait for process to exit
            await process.WaitForExitAsync();

        }
over 4 years ago · Santiago Trujillo Report

0

start.Start();
while (!start.StandardOutput.EndOfStream)
{
    string line = start.StandardOutput.ReadLine();
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!