函数中更改全局变量无效

2024-04-29

我刚刚尝试了这段代码:

$number = 2

Function Convert-Foo {
    $number = 3
}
Convert-Foo
$number

我期待这个功能Convert-Foo会改变$number到3,但仍然是2。

为什么不是全局变量$number通过函数改为3?


不,恐怕 PowerShell 不是这样设计的。你必须思考scopes,有关此主题的更多信息,请阅读 PowerShell 帮助关于范围 https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scopes?view=powershell-6#short-description或输入Get-Help about_scopes在您的 PowerShell ISE/控制台中。

简而言之,如果您想更改全局范围内的变量,则应该解决全局范围:

$number = 2

Function Convert-Foo {
    $global:number = 3
}
Convert-Foo
$number

在 a 内创建的所有变量Function在函数外部不可见,除非您将它们明确定义为Script or Global。最好的做法是保存result另一个变量中的函数,因此您可以在脚本范围内使用它:

$number = 5
    
Function Convert-Foo {
   # do manipulations in the function
   # and return the new value
   $number * 10
}

$result = Convert-Foo
    
# Now you can use the value outside the function:
"The result of the function is '$result'"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

函数中更改全局变量无效 的相关文章

随机推荐