2

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

1 回答 1

1

我不知道您要完成什么(对于处理脚本输出的简单目的,它看起来过于复杂)但是通过对您的 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.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 { "我在等待..."; 开始睡眠 - 毫秒 500 }

    $outputStream = $pipeline.EndInvoke($async)

    # 清理代码    
    $pipeline.Dispose()
    $异步 = $null
    $管道 = $null
    if ($runspacepool -ne $null) {$runspacepool.Close()}

    $输出流
`
于 2012-11-17T12:10:01.190 回答