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"
Variables are an integral part of PowerShell. There are many types of variables; this article will focus on global variables. Global variables are the ones which are available to all scripts, functions, or any cmdlet within the current session.
To declare a PowerShell global variable, simply use the below syntax. $global: myVariable ="This is my first global variable." If you choose not to give any value to it, you can explicitly assign a null value to it.
The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With