如何从脚本块中检索变量值(作业)

时间:2019-09-18 09:54:23

标签: powershell

我正在尝试获取在脚本块内修改的变量的值:

function Test-Function {
    $var = "apple"
    Start-Job -ScriptBlock {
        $var = "banana"
    }
    Write-Host "Variable is $var"
}
Test-Function
Variable is: apple

我正在尝试获取输出“香蕉”。这可能吗?

1 个答案:

答案 0 :(得分:3)

由于在代码中使用PS Jobs,因此需要使用wait-job使用wait等待作业完成,最后必须使用receive-job接收该作业。用以下代码替换您的代码:

function Test-Function {
    $var = "apple"
    Start-Job -ScriptBlock {
        $var = "banana"
        Write-Host "Variable is $var"
    } | Wait-Job -Any |Receive-Job

    #Write-Host "Variable is $var"
}
Test-Function

希望有帮助。