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

前端 未结 7 1293
北荒
北荒 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:57

    I ran across this question while troubleshooting my own code.

    So this does NOT work...

    $myLogText = ""
    function AddLog ($Message)
    {
        $myLogText += ($Message)
    }
    AddLog ("Hello")
    Write-Host $myLogText
    

    This APPEARS to work, but only in the PowerShell ISE:

    $myLogText = ""
    function AddLog ($Message)
    {
        $global:myLogText += ($Message)
    }
    AddLog ("Hello")
    Write-Host $myLogText
    

    This is actually what works in both ISE and command line:

    $global:myLogText = ""
    function AddLog ($Message)
    {
        $global:myLogText += ($Message)
    }
    AddLog ("Hello")
    Write-Host $global:myLogText
    

提交回复
热议问题