电源壳|如何以编程方式遍历变量名 [英] Powershell | how to programmatically iterate through variable names

查看:45
本文介绍了电源壳|如何以编程方式遍历变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

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

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

一旦达到value5,我会尝试让循环停止.问题是我如何传递所有变量,所以如果 $a1 不是 value5,它会转到 $a2.谢谢.

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.

推荐答案

你在尝试什么 ⚠️

您可以使用 Get 获取变量-变量 cmdlet.默认情况下,Get-Variable(以及对应的 Set-Variable) 将包括所有已知变量,包括您创建的其他变量(例如 $b1 = valueB1")、自动变量(例如 $args) 以及从父级继承的所有内容 范围.
因此,您需要非常小心地使用这些 cmdlet,因为您可能很容易检索或覆盖错误的变量.

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!.

使用 自定义变量列表"nofollow noreferrer">哈希表 并在其中读取和写入您的值:

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

这篇关于电源壳|如何以编程方式遍历变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆