Powershell gotchas: refer to variables outside a function

April 25, 2013

...

Consider the following code:

$x = 1
function changeit {
    "Changing `$x. Was: $x"
    $x = 2
    "New value: $x"
}
"`$x has value $x"
changeit
"`$x has value $x"

Not too complicated, right. Let’s see what happens when we run it:

$x has value 1
Changing $x. Was: 1
New value: 2
$x has value 1

What’s going on? Well, trying to change the value of $x inside the function did not work. Why not? What the statement $x = 2 actually does, is to create a local variable inside the function and give it the value of 2. Let’s fix that:

$x = 1
function changeit {
    "Changing `$x. Was: $x"
    $script:x = 2
    "New value: $x"
}
"`$x has value $x"
changeit
"`$x has value $x"

Now, we run it again:

$x has value 1
Changing $x. Was: 1
New value: 2
$x has value 2

The thing is that we have to explicitly tell Powershell to update the variable in the parent scope instead of creating a new variable in the current scope.


Profile picture

Written by Vidar Kongsli who is a software professional living in Oslo, Norway. Works as a consultant, system architect and developer at Bredvid. You should follow him on Twitter