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

前端 未结 7 1292
北荒
北荒 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:59

    You'll have to pass your arguments as reference types.

    #First create the variables (note you have to set them to something)
    $global:var1 = $null
    $global:var2 = $null
    $global:var3 = $null
    
    #The type of the reference argument should be of type [REF]
    function foo ($a, $b, [REF]$c)
    {
        # add $a and $b and set the requested global variable to equal to it
        # Note how you modify the value.
        $c.Value = $a + $b
    }
    
    #You can then call it like this:
    foo 1 2 [REF]$global:var3
    

提交回复
热议问题