Powershell: Capturing Standard Errors and Errors with a Process Object

I want to run a java program from powershell and get the results printed on the console.

I followed the instructions on this: Capturing standard errors and startup errors

But for me it did not work as I expect. What am I doing wrong?

This is the script:

$psi = New-object System.Diagnostics.ProcessStartInfo $psi.CreateNoWindow = $true $psi.UseShellExecute = $false $psi.RedirectStandardOutput = $true $psi.RedirectStandardError = $true $psi.FileName = 'java.exe' $psi.Arguments = @("-jar","tools\compiler.jar","--compilation_level", "ADVANCED_OPTIMIZATIONS", "--js", $BuildFile, "--js_output_file", $BuildMinFile) $process = New-Object System.Diagnostics.Process $process.StartInfo = $psi $process.Start() | Out-Null $process.WaitForExit() $output = $process.StandardOutput.ReadToEnd() $output 

The $ output variable is always empty (and, of course, nothing is printed on the console).

+17
java windows powershell
Jul 17 2018-12-21T00:
source share
2 answers

The documents in the RedirectStandardError property indicate that it is better to place a WaitForExit() call after a ReadToEnd() call. It 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 
+30
Jul 18 2018-12-18T00:
source share

A small variation that allows you to selectively print output, if necessary. As if you were only looking for error messages or warnings, and by the way, Kate, you saved my bacon with the answer ...

 $psi = New-object System.Diagnostics.ProcessStartInfo $psi.CreateNoWindow = $true $psi.UseShellExecute = $false $psi.RedirectStandardOutput = $true $psi.RedirectStandardError = $true $psi.FileName = 'robocopy' $psi.Arguments = @("$HomeDirectory $NewHomeDirectory /MIR /XF desktop.ini /XD VDI /R:0 /W:0 /s /v /np") $process = New-Object System.Diagnostics.Process $process.StartInfo = $psi [void]$process.Start() do { $process.StandardOutput.ReadLine() } while (!$process.HasExited) 
+11
Dec 27 '12 at 21:25
source share



All Articles