How to modify parent scope variable using Powershe

2020-08-09 08:16发布

I'm fairly new to powershell, and I'm just not getting how to modify a variable in a parent scope:

$val = 0
function foo()
{
    $val = 10
}
foo
write "The number is: $val"

When I run it I get:

The number is: 0

I would like it to be 10. But powershell is creating a new variable that hides the one in the parent scope.

I've tried these, with no success (as per the documentation):

$script:$val = 10
$global:$val = 10
$script:$val = 10

But these don't even 'compile' so to speak. What am I missing?

标签: powershell
4条回答
我想做一个坏孩纸
2楼-- · 2020-08-09 09:08

Let me point out a third alternative, even though the answer has already been made. If you want to change a variable, don't be afraid to pass it by reference and work with it that way.

$val=1
function bar ($lcl) 
{
    write "In bar(), `$lcl.Value starts as $($lcl.Value)"
    $lcl.Value += 9
    write "In bar(), `$lcl.Value ends as $($lcl.Value)"
}
$val
bar([REF]$val)
$val

That returns:

1
In bar(), $lcl.Value starts as 1
In bar(), $lcl.Value ends as 10
10
查看更多
看我几分像从前
3楼-- · 2020-08-09 09:11

You don't need to use the global scope. A variable with the same name could have been already exist in the shell console and you may update it instead. Use the script scope modifier. When using a scope modifier you don't include the $ sign in the variable name.

$script:val=10

查看更多
乱世女痞
4楼-- · 2020-08-09 09:12

I know this is crazy old but I had a similar question and found this post in my search and wanted to share the answer I found:

$val = 0
function foo {
    Set-Variable -scope 1 -Name "Val" -Value "10"
}
foo
write "The number is: $val"

More information can be found in the Microsoft Docs article About Scopes.


Be aware that recursive functions require the scope to be adjusted accordingly:

$val = ,0
function foo {
    $b = $val.Count
    Set-Variable -Name 'val' -Value ($val + ,$b) -Scope $b
    if ($b -lt 10) {
        foo
    }
}
查看更多
forever°为你锁心
5楼-- · 2020-08-09 09:13

If you want to use this then you could do something like this:

$global:val=0 
function foo()
{
    $global:val=10 
}
foo
write "The number is: $val"
查看更多
登录 后发表回答