我正在尝试在我的 PowerShell 脚本中处理来自管道的输出。现在我看到输出的唯一方法是当我发出 EndInvoke
管道的方法,但由于我的一些调用可能会长时间运行并且可能有很多输出,所以我希望能够在进程运行时显示输出。
看起来我可以通过将输入和输出参数传递给 BeginInvoke
来做到这一点。方法,但我似乎无法获得正确的语法。有什么建议么?我正在尝试的一个例子如下:
$scriptBlock = {param([int]$pauseTime = 10); Write-Output "Test"; Start-Sleep -Seconds $pauseTime; Write-Output "Test 2"}
# Create objects and set stuff up
$initialSessionState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()
$runspacepool = [Management.Automation.Runspaces.RunspaceFactory]::CreateRunspacePool(1, 4, $initialSessionState, $Host)
$runspacepool.Open()
$pipeline = [powershell]::Create().AddScript($scriptBlock).AddParameter("pauseTime", 30)
$pipeline.RunspacePool = $runspacepool
# These two lines are not correct
$inputStream = New-Object [System.Management.Automation]
$outputStream = New-Object [System.Management.Automation.PSDataCollection]
$async = $pipeline.BeginInvoke($inputStream, $outputStream)
# Do something with the $outputStream here???
$pipeline.EndInvoke($async)
# Clean-up code
$pipeline.Dispose()
$async = $null
$pipeline = $null
if ($runspacepool -ne $null) {$runspacepool.Close()}
最佳答案
我不知道您要完成什么(对于处理脚本输出的简单目的,它看起来过于复杂)但是通过对 PowerShell 脚本的这个小修改,至少您会得到一个输出:
` $scriptBlock = {
参数([int]$pauseTime = 1)
写输出“测试 1”
开始- sleep -秒 $pauseTime
写输出“测试 2”
}
# 创建对象并设置东西
$initialSessionState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()
$runspacepool = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspacePool(1, 4, $initialSessionState, $Host)
$runspacepool.Open()
$pipeline = [powershell]::Create().AddScript($scriptBlock).AddParameter("pauseTime", 5)
$pipeline.RunspacePool = $runspacepool
$outputStream = New-Object -Typename System.Management.Automation.PSDataCollection[PSObject]
$async = $pipeline.BeginInvoke()
1..10 | Foreach { "我在等待...";开始 sleep - 毫秒 500 }
$outputStream = $pipeline.EndInvoke($async)
# 清理代码
$pipeline.Dispose()
$异步 = $null
$管道 = $null
if ($runspacepool -ne $null) {$runspacepool.Close()}
$输出流
`
关于powershell - 在 Powershell 中使用带有 BeginInvoke 的 PSDataCollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11000801/