gpt4 book ai didi

PowerShell,运行外部进程时流处理输出和错误

转载 作者:行者123 更新时间:2023-12-02 22:55:13 26 4
gpt4 key购买 nike

我正在使用 PowerShell 脚本来执行控制台应用程序,并尝试从那里重定向标准输出和标准错误。我使用的代码如下:

$ProcessInfo = New-Object System.Diagnostics.ProcessStartInfo 
$ProcessInfo.FileName = "myExe.exe"
$ProcessInfo.Arguments = "bla bla bla"
$ProcessInfo.RedirectStandardError = $true
$ProcessInfo.RedirectStandardOutput = $true
$ProcessInfo.UseShellExecute = $false
$Process = New-Object System.Diagnostics.Process
$Process.StartInfo = $ProcessInfo

$Process.Start() | Out-Null
$output = $Process.StandardOutput.ReadToEnd()
$errors = $Process.StandardError.ReadToEnd()
$Process.WaitForExit()
$output
$errors

return $Process.ExitCode

到目前为止一切顺利,如果我有错误,我可以看到它被重定向到我的 PowerShell 控制台,如果我有输出,它也会被重定向。问题是这个过程需要 10 分钟,而在此期间我们不知道发生了什么。

在 PowerShell 中,有什么方法可以在进程运行时流式传输输出和错误的内容吗?在纯.NET中我们可以订阅Process类的事件,我可以在PowerShell中做同样的事情吗?

最佳答案

Is there any way in PowerShell I can stream the content of the Output and the Error while the process is running? In pure .NET we can subscribe to events of the Process class, can I do the same in PowerShell?

当然可以!您需要的是 Object Events :

An object event is a .Net object that not only has the usual Properties and Methods in the object, but also has another member called Event, which you can register a subscription on using Register-ObjectEvent

这里是来自 PowerShell forums 的示例,稍加修改。它将异步地从 ping 命令输出数据( at least from the script point of view ):

# Setup stdin\stdout redirection
$StartInfo = New-Object System.Diagnostics.ProcessStartInfo -Property @{
FileName = 'ping.exe'
Arguments = '-t 127.0.0.1'
UseShellExecute = $false
RedirectStandardOutput = $true
RedirectStandardError = $true
}

# Create new process
$Process = New-Object System.Diagnostics.Process

# Assign previously created StartInfo properties
$Process.StartInfo = $StartInfo

# Register Object Events for stdin\stdout reading
$OutEvent = Register-ObjectEvent -Action {
Write-Host $Event.SourceEventArgs.Data
} -InputObject $Process -EventName OutputDataReceived

$ErrEvent = Register-ObjectEvent -Action {
Write-Host $Event.SourceEventArgs.Data
} -InputObject $Process -EventName ErrorDataReceived

# Start process
[void]$Process.Start()

# Begin reading stdin\stdout
$Process.BeginOutputReadLine()
$Process.BeginErrorReadLine()

# Do something else while events are firing
do
{
Write-Host 'Still alive!' -ForegroundColor Green
Start-Sleep -Seconds 1
}
while (!$Process.HasExited)

# Unregister events
$OutEvent.Name, $ErrEvent.Name |
ForEach-Object {Unregister-Event -SourceIdentifier $_}

关于PowerShell,运行外部进程时流处理输出和错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23239127/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com