expirat001
expirat001

Reputation: 2205

Invoke-Expression in foreach

$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

Answers (2)

mjolinor
mjolinor

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

arco444
arco444

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

Related Questions