首页 > 解决方案 > 通过 Powershell 同步异步作业

问题描述

我有一个 PowerShell 函数,我需要将值从新作业获取到脚本中的变量,而无需“休眠脚本”。

我的想法类似于以下内容......

Function async() 
{
    $scriptblock = { 
                        #Do Something 
                        Start-Sleep -Seconds 60
                        write-output $argsfromFunction 
                   } 
    return $(
                start-job -ScriptBlock $scriptblock 
                          -ArgumentList $argsfromFunction 
            );
}
function getresult() 
{ 
    return $( get-job ( async() ) | receive-job ) 
}
#do it when the async() stop running without interrupt the script and set it to $global:var1

完成我的任务的简单方法是什么?谢谢您的帮助。

标签: powershellpowershell-5.0start-job

解决方案


我建议在处理工作之前多学习 PowerShell,因为它们需要对管道以及 PowerShell 如何处理输入和输出有更深入的了解。

但是您可以使用以下内容:

$jobToRun = Start-Job -ScriptBlock { #DoStuff }

while ( [Boolean]$( $jobToRun.JobStateInfo.state -ne "Completed" ) )
{
    # Do some stuff in script while job is running
}
$results = Receive-Job -Job $jobToRun

然后根据脚本块的输出,您可以解析$results出您想要的内容。您也不必在循环中等待作业完成,但如果作业未完成或需要很长时间,您需要有一种方法来处理。此外,一旦您对 PowerShell 更加熟悉,我强烈建议您研究运行空间而不是作业,因为每个作业都需要一个新的 PowerShell 实例,这可能会占用大量内存。Boe Prox 写了一篇关于如何利用它们的精彩文章,甚至提供了他自己的自定义模块,以使它们具有与作业类似的格式。

此外,如果您想将它们放在一个函数中,您可以将Start-Job/包裹Receive-Job在其中并将其设置为等于一个变量。您不需要在 PowerShell 中返回输出,因为 return 只是退出函数、脚本或脚本块的一种方式,函数内部语句的每个结果都将从函数输出返回,如果您想了解更多信息什么返回意味着你可以在这里:https ://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_return


推荐阅读