从 Start-Job -ScriptBlock 发起后的函数返回值

Function returning value after being initiated from Start-Job -ScriptBlock

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

调用该函数
Start-Job -Scriptblock { Set-SomeConfiguration -ComputerName $computer }

有什么方法可以检索 Set-SomeConfiguration 生成的布尔值吗?

是,使用 Receive-Job cmdlet:

$SomeJob = Start-Job { Set-SomeConfiguration -ComputerName $computer }
$Result  = $SomeJob | Receive-Job -Wait

-Wait 参数确保 Receive-Job 等待作业完成并 return 其结果。

(注意:大多数 Set-* cmdlet 不会 - 也不应该 - 实际上 return 任何东西。要实现你所描述的,你可以 return automatic variable $? 的值:{Set-SomeConfiguration;$?},或在接收 )

之前检查作业的 StateError 属性

如果您想更精细地控制等待时间,请使用 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