在foreach中调用表达式

时间:2015-02-16 15:48:18

标签: powershell

$test1 = {Get-Process}
$test2 = {Get-Process}
$test3 = {Get-Process}

我想在foreach中自动执行Invoke-Command。

我尝试了以下但没有工作:

1..3 | %{& ($("`$test$_"))}
1..3 | %{Invoke-Command "`$test$_"}

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

这有点不整洁,因为您需要运行invoke-expressioniex)来首先评估变量:

 1..3 | % { invoke-command $(iex "`$test$_") }

我建议只是将命令直接放入数组中,然后迭代它:

$cmds = @({Get-Process},{Get-Process},{Get-Process})
$cmds | % { Invoke-Command $_ }

答案 1 :(得分:1)

使用Get-Variable会更清晰:

$test1 = {Get-Process}
$test2 = {Get-Process}
$test3 = {Get-Process}

1..3 | foreach { .(Get-Variable test$_).value}
相关问题