2017-08-02 97 views
0

在此脚本的开头,我设置了一些变量($ 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++ 
} 

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

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

+7

集/新变量会做的伎俩,但为未来几代人的爱,请使用哈希表或数组 –

+0

啊好呼叫。它是阵列。 – highupinthenorth

回答

0

Invoke-Expression可以评估你的字符串,就好像它是作为命令输入

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