Reputation: 2205
$test1 = {Get-Process}
$test2 = {Get-Process}
$test3 = {Get-Process}
I want to execute an Invoke-Command automatically in a foreach.
I tried the following but not working :
1..3 | %{& ($("`$test$_"))}
1..3 | %{Invoke-Command "`$test$_"}
Thanks for your help
Upvotes: 0
Views: 1514
Reputation: 68293
That would be a lot cleaner using Get-Variable:
$test1 = {Get-Process}
$test2 = {Get-Process}
$test3 = {Get-Process}
1..3 | foreach { .(Get-Variable test$_).value}
Upvotes: 1
Reputation: 22831
This is a bit untidy because you need to run an invoke-expression
(iex
) to evaluate the variables first:
1..3 | % { invoke-command $(iex "`$test$_") }
I'd recommend just putting the commands directly into an array and iterating over that instead:
$cmds = @({Get-Process},{Get-Process},{Get-Process})
$cmds | % { Invoke-Command $_ }
Upvotes: 1