使用字符串+第二个变量创建变量

时间:2017-08-02 18:28:21

标签: powershell variables

在这个脚本的开头我设置了一些变量($ numof0 = 3,$ numof1 = 5等)。我想将所有这些变量写入控制台,但我想比下面的10个写主机语句更加简洁。

Write-Host "There are $numOf0 0's"
Write-Host "There are $numOf1 1's"
Write-Host "There are $numOf2 2's"
Write-Host "There are $numOf3 3's"
Write-Host "There are $numOf4 4's"
Write-Host "There are $numOf5 5's"
Write-Host "There are $numOf6 6's"
Write-Host "There are $numOf7 7's"
Write-Host "There are $numOf8 8's"
Write-Host "There are $numOf9 9's"

我认为既然所有变量都有相同的开头($ numof)并且所有变量都以越来越多的数字结尾,我可以做这样的事情......

$j=0
while($j -lt 10){
    $final = '$numof'+"$j"
    write-host "There are $final $j's"
    $j++
}

显然,变量$ final只是一个字符串,当打印到控制台时,不会显示我想要打印的相应$ numofX变量的内容。

有没有办法使用字符串和另一个变量(字符串'$ numof'和变量'$ j')创建一个变量($ final)并仍然引用$ numOfX变量的原始内容?

1 个答案:

答案 0 :(得分:0)

link可以评估您的字符串,就好像它被键入为命令一样

$j=0
while($j -lt 10){
    $final = Invoke-Expression -Command ('$numof'+"$j")
    write-host "There are $final $j's"
    $j++
}