Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a global PowerShell variable from a function where the global variable name is a variable passed to the function

Tags:

powershell

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.

like image 245
Radagast Avatar asked Sep 21 '12 17:09

Radagast


People also ask

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.

How do you assign a value to a global variable in a function?

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.

How do you assign a variable value to another variable in PowerShell?

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 .

How do you pass a variable to a function in PowerShell?

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.


1 Answers

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 
like image 140
latkin Avatar answered Sep 22 '22 00:09

latkin