我想从powershell启动一个Java程序,并获得打印在控制台上的结果。
我遵循这个问题的说明: 捕获标准输出和错误与启动过程
但对我来说,这不像我所期望的那样。 我做错了什么?
这是脚本:
$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
$ outputvariables总是空的(当然没有任何东西被打印在控制台上)。
RedirectStandardError
属性中的文档暗示了在ReadToEnd()
调用之后放置WaitForExit()
调用会更好。 以下工作对我来说是正确的:
$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
小的变化,以便您可以选择性地打印输出,如果需要的话。 如果你只是看错误或警告信息,顺便说一句Keith你把你的回应保存了下来
$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)