Capture program stdout and stderr to separate variables Capture program stdout and stderr to separate variables powershell powershell

Capture program stdout and stderr to separate variables


One option is to combine the output of stdout and stderr into a single stream, then filter.

Data from stdout will be strings, while stderr produces System.Management.Automation.ErrorRecord objects.

$allOutput = & myprogram.exe 2>&1$stderr = $allOutput | ?{ $_ -is [System.Management.Automation.ErrorRecord] }$stdout = $allOutput | ?{ $_ -isnot [System.Management.Automation.ErrorRecord] }


The easiest way to do this is to use a file for the stderr output, e.g.:

$output = & myprogram.exe 'argv[0]', 'argv[1]' 2>stderr.txt$err = get-content stderr.txtif ($LastExitCode -ne 0) { ... handle error ... }

I would also use $LastExitCode to check for errors from native console EXE files.


You should be using Start-Process with -RedirectStandardError -RedirectStandardOutput options. This other post has a great example of how to do this (sampled from that post below):

$pinfo = New-Object System.Diagnostics.ProcessStartInfo$pinfo.FileName = "ping.exe"$pinfo.RedirectStandardError = $true$pinfo.RedirectStandardOutput = $true$pinfo.UseShellExecute = $false$pinfo.Arguments = "localhost"$p = New-Object System.Diagnostics.Process$p.StartInfo = $pinfo$p.Start() | Out-Null$p.WaitForExit()$stdout = $p.StandardOutput.ReadToEnd()$stderr = $p.StandardError.ReadToEnd()Write-Host "stdout: $stdout"Write-Host "stderr: $stderr"Write-Host "exit code: " + $p.ExitCode