powershell循环通过指定的数字和diplay正确的变量

时间:2015-07-29 22:03:19

标签: powershell

我想要获得的是相应变量的结果列表,例如

C:\folder1
C:\folder2
C:\folder3
C:\folder4
C:\folder5
C:\folder6
C:\folder7
C:\folder8
C:\folder9
C:\folder10
C:\folder11
C:\folder12
C:\folder13
C:\folder14
C:\folder15
C:\folder16
C:\folder17
C:\folder18
C:\folder19
C:\folder20

这是我到目前为止所得到的

$variable1
$variable2
$variable3
$variable4
$variable5
$variable6
$variable7
$variable8
$variable9
$variable10
$variable11
$variable12
$variable13
$variable14
$variable15
$variable16
$variable17
$variable18
$variable19
$variable20

这是我的代码

param (
$variable = "C:\folder1\",
$variable2 = "C:\folder2\",
$variable3 = "C:\folder3\",
$variable4 = "C:\folder4\",
$variable5 = "C:\folder5\",
$variable6 = "C:\folder6\",
$variable7 = "C:\folder7\",
$variable8 = "C:\folder8\",
$variable9 = "C:\folder9\",
$variable10 = "C:\folder10\",
$variable11 = "C:\folder11\",
$variable12 = "C:\folder12\",
$variable13 = "C:\folder13\",
$variable14 = "C:\folder14\",
$variable15 = "C:\folder15\",
$variable16 = "C:\folder16\",
$variable17 = "C:\folder17\",
$variable18 = "C:\folder18\",
$variable19 = "C:\folder19\",
$variable20 = "C:\folder20\"
)

try {
1..20 | % {“$"+"variable$_”}
write-host ("$_")

}
catch [exception]
{
write-host ($_.[exception])
}

1 个答案:

答案 0 :(得分:0)

param (
$variable1 = "C:\folder1\",
$variable2 = "C:\folder2\",
$variable3 = "C:\folder3\",
$variable4 = "C:\folder4\",
$variable5 = "C:\folder5\",
$variable6 = "C:\folder6\",
$variable7 = "C:\folder7\",
$variable8 = "C:\folder8\",
$variable9 = "C:\folder9\",
$variable10 = "C:\folder10\",
$variable11 = "C:\folder11\",
$variable12 = "C:\folder12\",
$variable13 = "C:\folder13\",
$variable14 = "C:\folder14\",
$variable15 = "C:\folder15\",
$variable16 = "C:\folder16\",
$variable17 = "C:\folder17\",
$variable18 = "C:\folder18\",
$variable19 = "C:\folder19\",
$variable20 = "C:\folder20\"
)

try {
foreach ($_ in 1..20) {
$variable = "variable" + $_
write-host(get-variable $variable -valueonly)
}
remove-variable * -erroraction silentlyContinue

}
catch [exception]
{
write-host ($_.[exception])
}

这有效......谢谢你

返回

C:\folder1\
C:\folder2\
C:\folder3\
C:\folder4\
C:\folder5\
C:\folder6\
C:\folder7\
C:\folder8\
C:\folder9\
C:\folder10\
C:\folder11\
C:\folder12\
C:\folder13\
C:\folder14\
C:\folder15\
C:\folder16\
C:\folder17\
C:\folder18\
C:\folder19\
C:\folder20\