Powershell | how to programmatically iterate through variable names [duplicate]

时光怂恿深爱的人放手 提交于 2021-02-20 04:04:48

问题


I have this code:

$a1 = "value1"
$a2 = "value2"
$a3 = "value3"
$a4 = "value4"
$a5 = "value5"

DO {
    "Starting Loop $a1"
    $a1
    $a1++
    "Now `$a is $a1"
} Until ($a1 -eq "value5")

i try to make the loop stop once it reach value5. The question is how i can go pass through all the variables, so if $a1 is not value5 it go to $a2. Thanks.


回答1:


What you're trying ⚠️

You might get the variables using the Get-Variable cmdlet. By default the Get-Variable (and the counterpart Set-Variable) will include all known variables including other variables you created (e.g. $b1 = "valueB1"), automatic variables (e.g. $args) and everything that is inherited from a parent scope.
Therefore you need to be very careful with these cmdlets as you might easialy retrieve or overwrite the wrong variable.

$a1 = "value1"
$a2 = "value2"
$a3 = "value3"
$a4 = "value4"
$a5 = "value5"

$a = 1
DO {
    "Starting Loop `$a$a"
    Get-Variable -ValueOnly "a$a"
    Set-Variable "a$a" "NewValue$a"
    Get-Variable -ValueOnly "a$a"
    $a++
} Until ($a -gt 5)

But as already suggested, this is not the way you should do this!.

Instead

Create a new custom list of variables using a hash table and read and write your values in there:

$a = @{}                        # create a hash table
1..5 |% { $a[$_] = "value$_" }  # count from 1 to 5 ($_ is the current item)
$a[3]                           # display the $a[3]

value3


来源:https://stackoverflow.com/questions/65245014/powershell-how-to-programmatically-iterate-through-variable-names

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!