在 foreach 中调用表达式
Invoke-Expression in foreach
$test1 = {Get-Process}
$test2 = {Get-Process}
$test3 = {Get-Process}
我想在 foreach 中自动执行一个 Invoke-Command。
我尝试了以下方法但没有用:
1..3 | %{& ($("`$test$_"))}
1..3 | %{Invoke-Command "`$test$_"}
感谢您的帮助
这有点不整洁,因为您需要先 运行 一个 invoke-expression
(iex
) 来计算变量:
1..3 | % { invoke-command $(iex "`$test$_") }
我建议直接将命令放入数组中并对其进行迭代:
$cmds = @({Get-Process},{Get-Process},{Get-Process})
$cmds | % { Invoke-Command $_ }
使用 Get-Variable 会更简洁:
$test1 = {Get-Process}
$test2 = {Get-Process}
$test3 = {Get-Process}
1..3 | foreach { .(Get-Variable test$_).value}
$test1 = {Get-Process}
$test2 = {Get-Process}
$test3 = {Get-Process}
我想在 foreach 中自动执行一个 Invoke-Command。
我尝试了以下方法但没有用:
1..3 | %{& ($("`$test$_"))}
1..3 | %{Invoke-Command "`$test$_"}
感谢您的帮助
这有点不整洁,因为您需要先 运行 一个 invoke-expression
(iex
) 来计算变量:
1..3 | % { invoke-command $(iex "`$test$_") }
我建议直接将命令放入数组中并对其进行迭代:
$cmds = @({Get-Process},{Get-Process},{Get-Process})
$cmds | % { Invoke-Command $_ }
使用 Get-Variable 会更简洁:
$test1 = {Get-Process}
$test2 = {Get-Process}
$test3 = {Get-Process}
1..3 | foreach { .(Get-Variable test$_).value}