How to modify parent scope variable using Powershe

2020-08-09 08:13发布

问题:

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?

回答1:

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



回答2:

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


回答3:

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


回答4:

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"


标签: powershell