powershell - 通过 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 更加熟悉,我强烈建议您研究运行空间而不是作业,因为每个作业都需要一个新的 PowerShell 实例,这可能会占用大量内存。Boe Prox 写了一篇关于如何利用它们的精彩文章,甚至提供了他自己的自定义模块,以使它们具有与作业类似的格式。
此外,如果您想将它们放在一个函数中,您可以将Start-Job
/包裹Receive-Job
在其中并将其设置为等于一个变量。您不需要在 PowerShell 中返回输出,因为 return 只是退出函数、脚本或脚本块的一种方式,函数内部语句的每个结果都将从函数输出返回,如果您想了解更多信息什么返回意味着你可以在这里:https ://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_return
推荐阅读
- javascript - 如何在使用 JS 或 Jquery 悬停时向相应的 div 容器显示文本?
- java - 在我的 Macbook 上安装 PROM 时出现 Java 错误
- java - 将异常从匿名接口传递给方法签名
- python - 用 Python 计算
- android - 编译自定义 rom 时出错我尝试为我的设备编译 android 但没有任何效果
- python-3.x - python 2和python 3中的urlencode方法有区别吗
- python - django-role-permissions 不适用于事务?
- java - 如何为mybatis生成器在generateConfig.xml中设置domainObjectName后缀
- assembly - 简单的“Hello, World”程序在 Linux 程序集中不起作用
- javascript - eslint - vscode 的可选链接错误