[英]Sync async job via 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
完成任务的简单方法是什么? 谢谢您的帮助。
我建议在处理作业之前多学习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更加熟悉,我强烈建议您查看Runspaces而不是作业,因为每个作业都需要一个新的PowerShell实例,这可能会占用大量内存。 Boe Prox撰写了一篇关于利用它们的精彩文章,甚至提供了自己的自定义模块,使它们与作业类似。
此外,如果您想将它们放在一个函数中,您可以将Start-Job
/ Receive-Job
包装在其中并将其设置为等于变量。 您不需要在PowerShell中返回输出,因为return只是一种退出函数,脚本或脚本块的方法,函数内部语句的每个结果都将从函数输出返回,如果您想阅读更多内容返回意味着你可以在这里: https : //docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_return
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.