0

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?

1
  • Side note: In ISE, I get the expected result. But when running it from my .ps1, I get the above. Commented Feb 13, 2016 at 13:05

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This was pretty much what I was missing.... the declaration had to be added as $global: as well in order for it to work. I also agree that scoping to $script: is a much better overall option and worked as expected in my actual PS script. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.