我有一份超强的工作。
$cmd = {
param($a, $b)
$a++
$b++
}
$a = 1
$b = 2
Start-Job -ScriptBlock $cmd -ArgumentList $a, $b如何通过引用传递$a和$b,以便在作业完成时更新它们?或者,如何通过引用将变量传递给runspace?
发布于 2019-01-08 18:38:25
我刚刚写的简单示例(不要介意那些凌乱的代码)
# Test scriptblock
$Scriptblock = {
param([ref]$a,[ref]$b)
$a.Value = $a.Value + 1
$b.Value = $b.Value + 1
}
$testValue1 = 20 # set initial value
$testValue2 = 30 # set initial value
# Create the runspace
$Runspace = [runspacefactory]::CreateRunspace()
$Runspace.ApartmentState = [System.Threading.ApartmentState]::STA
$Runspace.Open()
# create the PS session and assign the runspace
$PS = [powershell]::Create()
$PS.Runspace = $Runspace
# add the scriptblock and add the argument as reference variables
$PS.AddScript($Scriptblock)
$PS.AddArgument([ref]$testValue1)
$PS.AddArgument([ref]$testValue2)
# Invoke the scriptblock
$PS.BeginInvoke()运行此命令后,将更新测试值的,因为它们是由ref传递的。
发布于 2019-01-08 19:31:50
正如@bluuf所指出的,在PowerShell中通过引用传递参数总是很笨拙,而且可能在PowerShell作业中也不起作用。
我可能会这样做:
$cmd = {
Param($x, $y)
$x+1
$y+1
}
$a = 1
$b = 2
$a, $b = Start-Job -ScriptBlock $cmd -ArgumentList $a, $b |
Wait-Job |
Receive-Job上面的代码将变量$a和$b传递给scriptblock,并在收到作业输出后将修改后的值赋回到变量。
https://stackoverflow.com/questions/54089109
复制相似问题