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

前端 未结 7 1294
北荒
北荒 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条回答
  •  旧时难觅i
    2020-12-04 16:58

    The first suggestion in latkin's answer seems good, although I would suggest the less long-winded way below.

    PS c:\temp> $global:test="one"
    
    PS c:\temp> $test
    one
    
    PS c:\temp> function changet() {$global:test="two"}
    
    PS c:\temp> changet
    
    PS c:\temp> $test
    two
    

    His second suggestion however about being bad programming practice, is fair enough in a simple computation like this one, but what if you want to return a more complicated output from your variable? For example, what if you wanted the function to return an array or an object? That's where, for me, PowerShell functions seem to fail woefully. Meaning you have no choice other than to pass it back from the function using a global variable. For example:

    PS c:\temp> function changet([byte]$a,[byte]$b,[byte]$c) {$global:test=@(($a+$b),$c,($a+$c))}
    
    PS c:\temp> changet 1 2 3
    
    PS c:\temp> $test
    3
    3
    4
    
    PS C:\nb> $test[2]
    4
    

    I know this might feel like a bit of a digression, but I feel in order to answer the original question we need to establish whether global variables are bad programming practice and whether, in more complex functions, there is a better way. (If there is one I'd be interested to here it.)

提交回复
热议问题