10

I have global variables and want to use them within a function.

I don't use local variables with the same name within the functions!

# Global variables:
$Var1 = @{ .. }
$Var2 = @( .. )
function testing{
    $Var1.keyX = "kjhkjh"
    $Var2[2]   = 6.89768
}

I do it and it works, but is it safe or do I have to use the following?

$Global:Var1.keyX = "kjhkjh"

1 Answer 1

23

In your function, you are modifying the contents of the hashtable so there is no need to use $global unless your function (or a function caller between your function and global scope) happens to have local variables $Var1 and $Var2 (BTW aren't you missing $). If this is all your own code then I'd say leave it as is. However, if you code allows other folks' code to call your function, then I would use the $global:Var1 specifier to make sure you're accessing the global variable and not inadvertently accessing a variable of the same name within a function that is calling your function.

Another thing to know about dynamic scoping in PowerShell is that when you assign a value to variable in a function and that variable happens to be a global e.g.:

$someGlobal = 7
function foo { $someGlobal = 42; $someGlobal }
foo
$someGlobal

PowerShell will do a "copy-on-write" operation on the variable $someGlobal within the function. If your intent was to really modify the global then you would use the $global: specifier:

$someGlobal = 7
function foo { $global:someGlobal = 42; $someGlobal }
foo
$someGlobal
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Keith (I changed my typo)! It is exactly what was a bit confusing: arrays and hashes (what else?) can be changed within a function without using $global: but normal variables cannot.
Basically you can change the contents of a referenced object (properties on an object, elements in an array, elements in a hashtable). What you can't change without use $global:<varname> is the actual object (array/hashtable) the variable references.

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.