Powershell: Capturing standard out and error with Process object

前端 未结 3 1061
轮回少年
轮回少年 2020-12-02 23:47

I want to start a Java program from PowerShell and get the results printed on the console.

I have followed the instructions of this question: Capturing standard out

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-03 00:12

    The docs on the RedirectStandardError property suggests that it is better to put the WaitForExit() call after the ReadToEnd() call. The following works correctly for me:

    $psi = New-object System.Diagnostics.ProcessStartInfo 
    $psi.CreateNoWindow = $true 
    $psi.UseShellExecute = $false 
    $psi.RedirectStandardOutput = $true 
    $psi.RedirectStandardError = $true 
    $psi.FileName = 'ipconfig.exe' 
    $psi.Arguments = @("/a") 
    $process = New-Object System.Diagnostics.Process 
    $process.StartInfo = $psi 
    [void]$process.Start()
    $output = $process.StandardOutput.ReadToEnd() 
    $process.WaitForExit() 
    $output
    

提交回复
热议问题