从作业中获取输出

Ric*_*hGK 1 powershell

我很难从工作中获得任何输出 - 以下代码出了什么问题?

$test = {
    DIR
}

$mjob = Start-Job -ScriptBlock {$test}
while (Get-Job -State Running){}
Receive-Job -Job $mjob -OutVariable $otest

Write-Host($otest)
Run Code Online (Sandbox Code Playgroud)

Kei*_*ill 7

当您-OutVariable仅使用提供变量的名称时,例如:

... -OutVariable otest
Run Code Online (Sandbox Code Playgroud)

除非$otest碰巧包含要将输出保存到的变量的名称.

其他一些建议. $test表示一个脚本块,因此您不需要放置{}它.而不是等待使用while循环,只需使用Wait-Jobeg:

$test = { get-childitem }
$job = Start-Job $test
Wait-Job $job
Receive-Job $job -OutVariable otest

$otest
Run Code Online (Sandbox Code Playgroud)

  • 当您指定`Start-Job -Sriptblock {$ test}`时,会创建一个*new*scriptblock,它将评估名为test的scriptblock中的变量.这将评估为null,因此您将无法获得输出. (2认同)