我正在尝试在我的 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()}