在Powershell中使用带有BeginInvoke的PSDataCollection



我正在尝试在我的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"    开始-睡眠-秒$pauseTime    写入输出"测试 2"   }    # 创建对象并设置内容    $initialSessionState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()    $runspacepool = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspacePool(1, 4, $initialSessionState, $Host)    $runspacepool。打开()    $pipeline = [powershell]::Create()。添加脚本($scriptBlock)。AddParameter("pauseTime", 5)    $pipeline。运行空间池 = $runspacepool    $outputStream = New-Object -Typename System.Management.Automation.PSDataCollection[PSObject]    $async = $pipeline。BeginInvoke()    1..10 |Foreach { "我在等...";启动-睡眠-毫秒 500 }    $outputStream = $pipeline。EndInvoke($async)    # 清理代码       $pipeline。Dispose()    $async = $null    $pipeline = $null    if ($runspacepool -ne $null) {$runspacepool.关闭()}    $outputStream`

最新更新