如何异步执行Powershell管道

时间:2014-10-14 06:25:21

标签: powershell asynchronous buffer pipeline

如何使Powershell异步执行管道而不是按顺序执行管道?

举例说明:

Function PipeDelay($Name, $Miliseconds){
    Process {
        Sleep -miliseconds $Miliseconds
        Write-Host "$Name : $_"
        $_        
    }
}

1..7 | PipeDelay Fast 100 | PipeDelay Slow 300 | PipeDelay Slowest 900

ISE和powershell中的输出如下:

Fast : 1
Slow : 1
Slowest : 1
1
Fast : 2
Slow : 2
Slowest : 2
2
Fast : 3
Slow : 3
Slowest : 3
3
...

就好像Powershell在处理下一个输入对象之前为一个输入对象顺序运行整个管道。执行看起来像这样:

Fast    :  1                         2                         3
Slow    :    1---1                     2---2                     3---3
Slowest :          1---------------1         2---------------2         3-----...

是否可以使用某些设置/环境变量/等。使管道独立/异步运行?也许有关于管道缓冲区大小等的设置?因此执行将看起来像这样:

Fast    :  1 2 3 4 5 6 7
Slow    :    1---1 2---2 3---3 4---4 5---5 6---6 7---7
Slowest :          1---------------1 2---------------2 3-----...

我认为这是因为STA / MTA模式。我完全不理解它们,但ISE(STA)/ Powershell Shell(MTA)中的相同结果似乎消除了STA / MTA模式的原因。

另外,我认为Write-Host是迫使顺序处理管道的问题,但即使我用Write-Host替换New-Event,顺序处理仍然适用。

1 个答案:

答案 0 :(得分:0)

我认为您不能以您想要的方式以异步方式利用管道,而不会因资源使用而变得昂贵。我试图捕捉你想要完成的精神,但以不同的方式。我使用了一个稍微不同的示例来说明[Automation.PowerShell]异步如何工作。

#1. You have a list of room requests you want to process in a function.  TimeToClean was added as a controllable thread block.
$roomsToClean = @( ([psCustomObject]@{Name='Bedroom';TimeToClean=2}),
                   ([psCustomObject]@{Name='Kitchen';TimeToClean=5}),
                   ([psCustomObject]@{Name='Bathroom';TimeToClean=3}),
                   ([psCustomObject]@{Name='Living room';TimeToClean=1}),
                   ([psCustomObject]@{Name='Dining room';TimeToClean=1}),
                   ([psCustomObject]@{Name='Foyier';TimeToClean=1})
                )


#2. We will clean three rooms and return a custom PowerShell object with a message.
Function Clean-Room{
     param([string]$RoomName,[int]$Seconds)

      Sleep -Seconds $Seconds
      Write-Output [psCustomObject] @{Message= "The robot cleaned the $RoomName in $Seconds seconds."}    
}


#3. Executing this list synchronously will result in an approximate 13 second runtime.
Write-Host "===== Synchronous Results =====" -ForegroundColor Green

$stopwatch =  [system.diagnostics.stopwatch]::StartNew()
foreach($item in $roomsToClean){
    $obj = Clean-Room $item.Name $item.TimeToClean
    Write-Output $obj.Message
}

$stopwatch.Stop()
Write-Host "Execution time for synchronous function was $($stopwatch.Elapsed)." -ForegroundColor Green


#4. Now let's run this function asynchronously for all of these items. Expected runtime will be approximately 5 seconds.


#=============== Setting up an ansynchronous powerShell Automation object and attaching it to a runspace.
#Many [Automation.PowerShell] objects can be attached to a given Runspace pool and the Runspace pool will manage queueing/dequeueing of each PS object as it completes.

#Create a RunSpace pool with 5 runspaces.  The pool will manage the 
#Many PowerShell autom
$minRunSpaces = 2
$maxRunsSpaces = 5
$runspacePool = [RunspaceFactory]::CreateRunspacePool($minRunSpaces, $maxRunsSpaces)    
$runspacePool.ApartmentState = 'STA'   #MTA = Multithreaded apartment  #STA = Singl-threaded apartment.
$runspacePool.Open()  #runspace pool must be opened before it can be used.

#For each room object, create an [Automation.PowerShell] object and attach it to the runspace pool.
#Asynchronously invoke the function for all objects in the collection.
$ps_collections = foreach($room in $roomsToClean){
                    try{

                    $ps = [System.Management.Automation.PowerShell]::Create() 
                    $ps.RunspacePool = $runspacePool

                    #Add your custom functions to the [Automation.PowerShell] object.
                    #Add argument with parameter name for readability. You may just use AddArgument as an alternative but know your positional arguments.

                    [void] $ps.AddScript(${function:Clean-Room})
                    [void] $ps.AddParameter('RoomName',$room.Name)        #Add parameterName,value
                    [void] $ps.AddParameter('Seconds',$room.TimeToClean)  #Add parameterName,value

                    #extend the ps management object to include AsyncResult and attach the AsyncResult object for receiving results at a later time.
                    $ps | Add-Member -MemberType NoteProperty -Name 'AsyncResult' -Value $ps.BeginInvoke()  #invoke asynchronously
                    $ps | Add-Member -MemberType ScriptMethod -Name 'GetAsyncResult' -Value {$this.EndInvoke($this.AsyncResult) } -PassThru
                    }
                    catch{
                        throw $_  #handle custom error here.
                    }
                }




#After the function has been asynchronously called for all room objects, Grab results from asynchronous function calls.
Write-Host "===== Asynchronous Results =====" -ForegroundColor Green
$stopwatch =  [system.diagnostics.stopwatch]::StartNew()
foreach($ps in $ps_collections){
    $obj = $ps.GetAsyncResult()
    [void] $ps.Dispose()  #dispose of object after use.
    Write-Output $obj.Message
}

$stopwatch.Stop()
Write-Host "Execution time for asynchronous function was 
$($stopwatch.Elapsed)." -ForegroundColor Green

#Runspace cleanup.
If($runspacePool){
    [void] $runspacePool.Close()
    [void] $runspacePool.Dispose()
}

结果时间会略有不同,但应与此类似:

=====同步结果=====

机器人在2秒内清理了卧室。

机器人在5秒内清理了厨房。

机器人在3秒内清洁了浴室。

机器人在1秒内清理了起居室。

机器人在1秒内清理了餐厅。

机器人在1秒内清理了Foyier。

同步功能的执行时间为00:00:13.0719157。

=====异步结果=====

机器人在2秒内清理了卧室。

机器人在5秒内清理了厨房。

机器人在3秒内清洁了浴室。

机器人在1秒内清理了起居室。机器人在1秒钟内清理了餐厅。

机器人在1秒内清理了Foyier。

异步功能的执行时间为00:00:04.9909951。