Search code examples
arrayspowershellscoping

Powershell scoping change?


I've been having an issue with updating a global variable in a function. I found the following article, which looked promising:

Variable scoping in PowerShell

However, I discovered that nothing he posted matched the output I saw. Here's his code:

$array=@("g")
function foo()
{
    $array += "h"
    Write-Host $array
}

& {
    $array +="s"
    Write-Host $array
}
foo

Write-Host $array

And his results:

g s
g h
g

However... My results on PowerShell 5.0 are:

s
h
g

Adding the suggested solution of $global:array += "s" gives:

g
h
g

What am I missing and how do I rectify it? How can I update a variable that is outside of a function from within a function if $global: doesn't work?


Solution

  • The array is declared at script scope, not global. Either declare the array as a global variable as well:

    $global:array=@("g")
    

    or use script scope to update it:

    $script:array += "h"
    

    I'd suggest the latter because using global variables for things only your script needs is a bit superfluous.