从Start-Job -ScriptBlock启动后返回值的函数

Ma *_* Ti -2 powershell jobs

想象一下,您创建了返回布尔值的函数(例如Set-SomeConfiguration).然后,你用它调用该函数

Start-Job -Scriptblock { Set-SomeConfiguration -ComputerName $computer }
Run Code Online (Sandbox Code Playgroud)

有没有办法检索由Set-SomeConfiguration?生成的布尔值?

Mat*_*sen 5

是的,使用Receive-Jobcmdlet:

$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;$?},或在接收之前检查作业的属性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
Run Code Online (Sandbox Code Playgroud)