Powershell:使用Process对象捕获标准输出和错误

Mar*_*Zen 21 java windows powershell

我想从PowerShell启动一个Java程序,并在控制台上打印结果.

我已按照此问题的说明操作: 使用Start-Process捕获标准输出和错误

但对我来说,这不符合我的预期.我做错了什么?

这是脚本:

$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
Run Code Online (Sandbox Code Playgroud)

$output变量总是空的(并且没有打印过程的控制台上).

Kei*_*ill 37

RedirectStandardError物业的文档表明,最好在WaitForExit()通话后ReadToEnd()拨打电话.以下对我来说正常:

$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
Run Code Online (Sandbox Code Playgroud)


小智 16

变化小,以便您可以根据需要选择性地打印输出.如果您只是寻找错误或警告信息,并且按照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)
Run Code Online (Sandbox Code Playgroud)

  • 我遇到了这种方法的问题,当进程由于错误而退出时,比如说,ReadLine()无法赶上,因此输出被截断. (3认同)