想象一下,您创建了返回布尔值的函数(例如Set-SomeConfiguration
).然后,你用它调用该函数
Start-Job -Scriptblock { Set-SomeConfiguration -ComputerName $computer }
Run Code Online (Sandbox Code Playgroud)
有没有办法检索由Set-SomeConfiguration
?生成的布尔值?
是的,使用Receive-Job
cmdlet:
$SomeJob = Start-Job { Set-SomeConfiguration -ComputerName $computer }
$Result = $SomeJob | Receive-Job -Wait
Run Code Online (Sandbox Code Playgroud)
该-Wait
参数确保Receive-Job
等待作业完成并返回其结果.
(注意:大多数Set-*
cmdlet不会 - 也不应该 - 实际返回任何内容.要实现您描述的内容,您可以返回自动变量$?
的值:{Set-SomeConfiguration;$?}
,或在接收之前检查作业的属性State
和Error
属性)
如果您想要更精细地控制您想要等待多长时间,请使用Wait-Job
.
在这个例子中,我们等待10秒(或直到作业完成):
# Job that takes a variable amount of time
$Job = Start-Job -ScriptBlock {
Start-Sleep -Seconds $(5..15 | Get-Random)
return "I woke up!"
}
# Wait for 10 seconds
if(Wait-Job $Job -Timeout 10){
# Job returned before timeout, let's grab results
$Results = $Job | Receive-Job
} else {
# Job did not return in time
# You can log, do error handling, defer to a default value etc. in here
}
# Clean up
Get-Job | Remove-Job
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2706 次 |
最近记录: |