Powershell 从脚本块获取返回值

Powershell 从脚本块获取返回值,powershell,powershell-3.0,Powershell,Powershell 3.0,我按照链接中的示例创建了一个脚本。但是,我需要在最后列出脚本块的返回值$result。如何修改脚本来完成它 $maxConcurrentJobs = 3; # Read the input and queue it up $jobInput = get-content .\input.txt $queue = [System.Collections.Queue]::Synchronized( (New-Object System.Collections.Queue) ) foreach($it

我按照链接中的示例创建了一个脚本。但是,我需要在最后列出脚本块的返回值$result。如何修改脚本来完成它

$maxConcurrentJobs = 3;

# Read the input and queue it up
$jobInput = get-content .\input.txt
$queue = [System.Collections.Queue]::Synchronized( (New-Object System.Collections.Queue) )
foreach($item in $jobInput)
{
    $queue.Enqueue($item)
}

# Function that pops input off the queue and starts a job with it
function RunJobFromQueue
{
    if( $queue.Count -gt 0)
    {
        $j = Start-Job -ScriptBlock {
           param($x); 
           #..... 
           $result ######### Need this value returned to the main script
           } -ArgumentList $queue.Dequeue()
        Register-ObjectEvent -InputObject $j -EventName StateChanged -Action { 
           RunJobFromQueue; 
           Unregister-Event $eventsubscriber.SourceIdentifier; 
           Remove-Job $eventsubscriber.SourceIdentifier 
           } | Out-Null
    }
}

# Start up to the max number of concurrent jobs
# Each job will take care of running the rest
for( $i = 0; $i -lt $maxConcurrentJobs; $i++ )
{
    RunJobFromQueue
}
######## Process a list of $result

将$result序列化为文件

当您到达“处理$result列表”点时,查找文件并反序列化它们

注意:您必须找到一种很好的方法来确定异步作业何时首先完成!可能使用job name=$result file name,如果$result file name=一个不存在的作业名称,则可以在删除完成的作业之前安全地打开

添加一个接收作业$eventsubscriber.SourceIdentifier,并且不要将输出导入Out Null