Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/amazon-s3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell 如何从脚本块(作业)检索变量值_Powershell - Fatal编程技术网

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

Powershell 如何从脚本块(作业)检索变量值,powershell,Powershell,我试图获取在scriptblock中修改的变量的值: function Test-Function { $var = "apple" Start-Job -ScriptBlock { $var = "banana" } Write-Host "Variable is $var" } Test-Function Variable is: apple 我正在尝试获取输出“香蕉”。这是可能的吗?因为您在代码中使用PS作业,所以需要使用wait等待作业使

我试图获取在scriptblock中修改的变量的值:

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

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

因为您在代码中使用PS作业,所以需要使用wait等待作业使用wait job完成,最后必须使用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
希望对您有所帮助。

可能的副本