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

前端 未结 7 1283
北荒
北荒 2020-12-04 16:17

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,         


        
7条回答
  •  北海茫月
    2020-12-04 16:49

    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
    

提交回复
热议问题