从函数中设置全局PowerShell变量,其中全局变量名是传递给函数的变量

Rad*_*ast 48 powershell

我需要从函数设置一个全局变量,我不太清楚如何做到这一点.

# Set variables
$global:var1
$global:var2
$global:var3

function foo ($a, $b, $c)
{
    # Add $a and $b and set the requested global variable to equal to it
    $c = $a + $b
}
Run Code Online (Sandbox Code Playgroud)

调用函数:

foo 1 2 $global:var3
Run Code Online (Sandbox Code Playgroud)

最终结果:

$ global:var3设置为3

或者如果我这样调用函数:

foo 1 2 $global:var2
Run Code Online (Sandbox Code Playgroud)

最终结果:

$ global:var2设置为3

我希望这个例子有意义.传递给函数的第三个变量是要设置的变量的名称.

lat*_*kin 84

您可以使用Set-Variablecmdlet.传$global:var3价值$var3,这是不是你想要的.你想发送名字.

$global:var1 = $null

function foo ($a, $b, $varName)
{
   Set-Variable -Name $varName -Value ($a + $b) -Scope Global
}

foo 1 2 var1
Run Code Online (Sandbox Code Playgroud)

不过,这不是很好的编程习惯.下面会更简单,以后不太可能引入错误:

$global:var1 = $null

function ComputeNewValue ($a, $b)
{
   $a + $b
}

$global:var1 = ComputeNewValue 1 2
Run Code Online (Sandbox Code Playgroud)


小智 39

很简单:

$A="1"
function changeA2 () { $global:A="0"}
changeA2
$A
Run Code Online (Sandbox Code Playgroud)

  • @Schiavini - 我认为它确实有效.如果它让你失望,请记住第一个'$ A`,如果直接在cmd行输入,则为global,并且*在全局范围内尝试时应该被覆盖.如果需要,请尝试添加"$ global:A"行.这是一个通过分号的单线程,它接受参数并执行相同的操作:`$ A = -777;函数changeA2($ p1,$ p2){$ global:A = $ p1 + $ p2}; changeA2 4 5; $ A; "显性全球:"+ $全球:A;`现在这是一个可怕的意大利面条代码?这是一个单独的讨论.; ^)我偏向拉特金的第二个解决方案. (2认同)

zda*_*dan 17

您必须将参数作为引用类型传递.

#First create the variables (note you have to set them to something)
$global:var1 = $null
$global:var2 = $null
$global:var3 = $null

#The type of the reference argument should be of type [REF]
function foo ($a, $b, [REF]$c)
{
    # add $a and $b and set the requested global variable to equal to it
    # Note how you modify the value.
    $c.Value = $a + $b
}

#You can then call it like this:
foo 1 2 [REF]$global:var3
Run Code Online (Sandbox Code Playgroud)

  • 我认为在PoSH中最接近真正返回值的是使用_local变量传递值并且永远不要使用`return`,因为它可能被任何输出情况"损坏"`函数CheckRestart([ REF] $ retval){#Some logic $ retval.Value = $ true} [bool] $ restart = $ false CheckRestart([REF] $ restart)if($ restart){Restart-Computer -Force}` (2认同)

da_*_*ker 17

我在对自己的代码进行故障排除时遇到了这个问题

所以这不起作用......

$myLogText = ""
function AddLog ($Message)
{
    $myLogText += ($Message)
}
AddLog ("Hello")
Write-Host $myLogText
Run Code Online (Sandbox Code Playgroud)

这个APPEARS可以工作,但只能在PowerShell ISE中使用:

$myLogText = ""
function AddLog ($Message)
{
    $global:myLogText += ($Message)
}
AddLog ("Hello")
Write-Host $myLogText
Run Code Online (Sandbox Code Playgroud)

这实际上适用于ISE和命令行:

$global:myLogText = ""
function AddLog ($Message)
{
    $global:myLogText += ($Message)
}
AddLog ("Hello")
Write-Host $global:myLogText
Run Code Online (Sandbox Code Playgroud)