如何从函数调用变量


function test{
for($a=0;$a -le 2;$a++){
if($a -eq 1){break}
}
}
#----outside----
write-output $a

如何从函数调用变量而不使用return来获取$a

除了使用 Rob 答案中描述的作用域外,还可以通过引用发送参数。

这意味着在函数内部,使用了对原始变量的引用,因此无论函数对它做什么,原始值都会受到影响。

缺点是,使用引用时,必须使用 System.Management.Automation.PSReference 类型的Value属性来访问/更改数据,如下例所示:

function test ([ref]$a) {
for ($a.Value = 0; $a.Value -le 2; $a.Value++){
if ($a.Value -eq 1) {break}
}
}
#----outside----
$a = 0 
test ([ref]$a)  # the parameter needs to be wrapped inside brackets and prefixed by [ref]
Write-Output $a

当发送对象类型的参数(例如 Hashtable(时,默认情况下它始终通过引用传递给函数,对于那些不使用[ref]acccellerator 的参数。

您是否尝试过将变量设置为全局变量?

$var="Test"
function test()
{
$global:var="blub"
}
test
$var

$a = 0
function test{
for($global:a=0;$global:a -le 2;$global:a++){
if($global:a -eq 1){break}
}
}
test
write-output $a

最新更新