Powershell:使用过程对象捕获标准输出和错误 [英] Powershell: Capturing standard out and error with Process object
问题描述
我想从PowerShell启动Java程序并将结果打印在控制台上.
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 and error with Start-Process
但是对我来说,这不符合我的预期.我在做什么错了?
But for me, this is not working as I expected. What I'm doing wrong?
这是脚本:
$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
$output
变量始终为空(当然,控制台上不会打印任何内容).
The $output
variable is always empty (and nothing is printed on the console of course).
推荐答案
RedirectStandardError
属性上的文档表明,最好将WaitForExit()
调用放在ReadToEnd()
调用之后.以下内容对我来说是正确的:
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
这篇关于Powershell:使用过程对象捕获标准输出和错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!