Powershell 从开始作业-脚本块启动后返回的函数值

Powershell 从开始作业-脚本块启动后返回的函数值,powershell,jobs,Powershell,Jobs,假设您创建了返回布尔值的函数(例如,Set SomeConfiguration)。然后,用 Start-Job -Scriptblock { Set-SomeConfiguration -ComputerName $computer } 是否有任何方法可以检索由Set SomeConfiguration生成的布尔值?是,使用cmdlet: -Wait参数确保接收作业等待作业完成并返回其结果 (注意:大多数Set-*cmdlet不会也不应该实际返回任何内容。要实现您所描述的,您可以返回:{Set

假设您创建了返回布尔值的函数(例如,
Set SomeConfiguration
)。然后,用

Start-Job -Scriptblock { Set-SomeConfiguration -ComputerName $computer }
是否有任何方法可以检索由
Set SomeConfiguration
生成的布尔值?

是,使用cmdlet:

-Wait
参数确保
接收作业
等待作业完成并返回其结果

(注意:大多数
Set-*
cmdlet不会也不应该实际返回任何内容。要实现您所描述的,您可以返回:
{Set SomeConfiguration;$?}
的值,或者在接收前检查作业的
状态
错误
属性)


如果您想更精确地控制等待的时间,请使用

在本例中,我们等待10秒(或直到作业完成):


您不仅仅是在寻找
接收作业
$SomeJob = Start-Job { Set-SomeConfiguration -ComputerName $computer }
$Result  = $SomeJob | Receive-Job -Wait
# 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