使用 Start-Process 捕获标准输出和错误 [英] Capturing standard out and error with Start-Process

查看:45
本文介绍了使用 Start-Process 捕获标准输出和错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在访问 StandardErrorStandardOutput 属性时,PowerShell 的 Start-Process 命令是否存在错误?

Is there a bug in PowerShell's Start-Process command when accessing the StandardError and StandardOutput properties?

如果我运行以下命令,则没有输出:

If I run the following I get no output:

$process = Start-Process -FilePath ping -ArgumentList localhost -NoNewWindow -PassThru -Wait
$process.StandardOutput
$process.StandardError

但是如果我将输出重定向到一个文件,我会得到预期的结果:

But if I redirect the output to a file I get the expected result:

$process = Start-Process -FilePath ping -ArgumentList localhost -NoNewWindow -PassThru -Wait -RedirectStandardOutput stdout.txt -RedirectStandardError stderr.txt

推荐答案

Start-Process 是出于某种原因设计的.这是一种无需发送到文件即可获取它的方法:

That's how Start-Process was designed for some reason. Here's a way to get it without sending to file:

$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "ping.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = "localhost"
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
$stdout = $p.StandardOutput.ReadToEnd()
$stderr = $p.StandardError.ReadToEnd()
Write-Host "stdout: $stdout"
Write-Host "stderr: $stderr"
Write-Host "exit code: " + $p.ExitCode

这篇关于使用 Start-Process 捕获标准输出和错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆