本文介绍了如何通过引用 Powershell 作业或运行空间来传递变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 Powershell 工作.
I have Powershell job.
$cmd = {
param($a, $b)
$a++
$b++
}
$a = 1
$b = 2
Start-Job -ScriptBlock $cmd -ArgumentList $a, $b
如何通过引用传递 $a
和 $b
以便在工作完成后更新它们?或者如何通过引用运行空间来传递变量?
How to pass $a
and $b
by a reference so when the job is done they will be updated? Alternatively how to pass variables by reference to runspaces?
推荐答案
我刚写的简单示例(不要介意乱码)
Simple sample I just wrote (don't mind the messy code)
# 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 传递的.
After running this the for the testvalues are updated since they are passed by ref.
这篇关于如何通过引用 Powershell 作业或运行空间来传递变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!