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



在这个脚本的开头,我设置了一些变量($numof 0 = 3,$numof 1 = 5,等等(。我想将所有这些变量写入控制台,但我想比下面的 10 个 write-host 语句更简洁。

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变量的内容。

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

Invoke-Expression 可以计算您的字符串,就好像它是作为命令键入的一样

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

最新更新