Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variables and local variables in PowerShell

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"
like image 892
gooly Avatar asked Jun 26 '14 16:06

gooly


People also ask

What is global variable in PowerShell?

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.

How do you set a global variable in PowerShell?

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.

Why we use $_ in PowerShell?

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.


1 Answers

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
like image 111
Keith Hill Avatar answered Oct 16 '22 12:10

Keith Hill