Search code examples
arrayspowershellinvoke-command

Invoke-Command with Computers array, access single array element inside scriptblock


I am wondering how to accomplish the following and hope you can help:

I want to execute several tasks on different computers by providing a array of computernames using

Invoke-Command -ComputerName $ComputerNameArray -ScriptBlock { ...}

Inside the scriptblock, I want to access the current ComputerName (not the whole array).

How is this possible?

I tried enclosing the Invoke-Command within a foreach loop, something like this:

foreach ($Computer in $ComputerNameArray)
{
 Invoke-Command-ComputerName $Computer -ScriptBlock { ...}
}

which works, this way I can access the current ComputerName with $env:Computer but as the foreach isn't necessary here, I want to get rid of it.

Any ideas?

Thanks all!


Solution

  • This works for me:

    Invoke-Command $ComputerNameArray { $env:computername }