Calling dynamic variable in PowerShell

后端 未结 2 1177
灰色年华
灰色年华 2020-12-02 00:30

I am trying to create a new variable that would use other variable with dynamic name as its value. Here\'s what I am trying to do:

I have a System.Array with two val

2条回答
  •  一生所求
    2020-12-02 01:10

    You want to use Invoke-Expression cmdlet. You need to create dynamic string expression of commands that would initialize variable with the value. Here's how you do it:

    $Years = 2015, 2016, 2017, 2018
    $Years | ForEach-Object { 
        $Year = $_
        Invoke-Expression ('$Year' + $Year + ' = "Year is ' + $Year + '"')
     }
    

    Here's the output:

    Get-Variable Year*
    
    Name                           Value                                                                                                                                                                                                                             
    ----                           -----                                                                                                                                                                                                                             
    Year                           2018                                                                                                                                                                                                                              
    Year2015                       Year is 2015                                                                                                                                                                                                                      
    Year2016                       Year is 2016                                                                                                                                                                                                                      
    Year2017                       Year is 2017                                                                                                                                                                                                                      
    Year2018                       Year is 2018                                                                                                                                                                                                                      
    Years                          {2015, 2016, 2017, 2018}         
    

提交回复
热议问题