3

I just tried this code:

$number = 2

Function Convert-Foo {
    $number = 3
}
Convert-Foo
$number

I expected that function Convert-Foo would change $number to 3, but it is still 2.

Why isn't the global variable $number changed to 3 by the function?

1 Answer 1

8

No, I'm afraid PowerShell isn't designed that way. You have to think in scopes, for more information on this topic please read the PowerShell help about scopes or type Get-Help about_scopes in your PowerShell ISE/Console.

The short answer is that if you want to change a variable that is in the global scope, you should address the global scope:

$number = 2

Function Convert-Foo {
    $global:number = 3
}
Convert-Foo
$number

All variables created inside a Function are not visible outside of the function, unless you explicitly defined them as Script or Global. It's best practice to save the result of a function in another variable, so you can use it in the script scope:

$number = 5
    
Function Convert-Foo {
   # do manipulations in the function
   # and return the new value
   $number * 10
}

$result = Convert-Foo
    
# Now you can use the value outside the function:
"The result of the function is '$result'"
Sign up to request clarification or add additional context in comments.

Comments

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.