从函数设置全局 PowerShell 变量,其中全局变量名称是传递给函数的变量 [英] Setting a global PowerShell variable from a function where the global variable name is a variable passed to the function

查看:89
本文介绍了从函数设置全局 PowerShell 变量,其中全局变量名称是传递给函数的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从函数中设置一个全局变量,但我不太确定如何去做.

I need to set a global variable from a function and am not quite sure how to do it.

# 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
}

调用函数:

foo 1 2 $global:var3

最终结果:

$global:var3 设置为 3

$global:var3 is set to 3

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

Or if I called the function like this:

foo 1 2 $global:var2

最终结果:

$global:var2 设置为 3

$global:var2 is set to 3

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

I hope this example makes sense. The third variable passed to the function is the name of the variable it is to set.

推荐答案

您可以使用 Set-Variable cmdlet.传递 $global:var3 会发送 $var3value,这不是您想要的.您想发送姓名.

You can use the Set-Variable cmdlet. Passing $global:var3 sends the value of $var3, which is not what you want. You want to send the name.

$global:var1 = $null

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

foo 1 2 var1

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

This is not very good programming practice, though. Below would be much more straightforward, and less likely to introduce bugs later:

$global:var1 = $null

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

$global:var1 = ComputeNewValue 1 2

这篇关于从函数设置全局 PowerShell 变量,其中全局变量名称是传递给函数的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆