Capture program stdout and stderr to separate variables

后端 未结 5 1399
小蘑菇
小蘑菇 2020-11-28 10:29

Is it possible to redirect stdout from an external program to a variable and stderr from external programs to another variable in one run?

For example:



        
5条回答
  •  庸人自扰
    2020-11-28 10:58

    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] }
    

提交回复
热议问题