I need to set a global variable from a function and am not quite sure how to do it.
# Set variables $global:var1 $global:var2 $global:var3 function foo ($a, $b, $c) { # Add $a and $b and set the requested global variable to equal to it $c = $a + $b }
Call the function:
foo 1 2 $global:var3
End result:
$global:var3 is set to 3
Or if I called the function like this:
foo 1 2 $global:var2
End result:
$global:var2 is set to 3
I hope this example makes sense. The third variable passed to the function is the name of the variable it is to set.
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.
Use of “global†keyword to modify global variable inside a function. If your function has a local variable with same name as global variable and you want to modify the global variable inside function then use 'global' keyword before the variable name at start of function i.e.
Working with variables To create a new variable, use an assignment statement to assign a value to the variable. You don't have to declare the variable before using it. The default value of all variables is $null . To get a list of all the variables in your PowerShell session, type Get-Variable .
You can pass variables to functions by reference or by value. When you pass a variable by value, you are passing a copy of the data. In the following example, the function changes the value of the variable passed to it. In PowerShell, integers are value types so they are passed by value.
You can use the Set-Variable
cmdlet. Passing $global:var3
sends the value of $var3
, which is not what you want. You want to send the name.
$global:var1 = $null function foo ($a, $b, $varName) { Set-Variable -Name $varName -Value ($a + $b) -Scope Global } foo 1 2 var1
This is not very good programming practice, though. Below would be much more straightforward, and less likely to introduce bugs later:
$global:var1 = $null function ComputeNewValue ($a, $b) { $a + $b } $global:var1 = ComputeNewValue 1 2
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