How to Invoke-Command the same function on remote computers in the same time (parallel) How to Invoke-Command the same function on remote computers in the same time (parallel) powershell powershell

How to Invoke-Command the same function on remote computers in the same time (parallel)


Invoke-Command already executes calls against each computer in parallel, as part of built-in functionality:

One-to-Many Remoting

The real power of remoting is the ability to send a command, in parallel, to one or more remote computers. Each remote computer executes the command, serializes the resulting objects into XML and transmits the results to your computer over the network.

Your computer receives the XML and deserializes it back into static objects. This lets you work with the command output in pretty much the same way as any other command output.

It all starts with the Invoke-Command cmdlet. In its simplest form, you simply specify a command to run, in the form of a scriptblock, and one or more computers upon which to run that command. For example, to read a list of computer names from a text file (one name per line) and run a command on each of them, use:

Invoke-Command –scriptblock { Get-EventLog Security –newest 200 } –computername (Get-Content computernames.txt)

When results come in to your computer, they’ll have an additional property attached called PSComputerName. This lets you see which result came from which computer. This is helpful because they might not all be received in the same order.

The -ComputerName parameter can take a list/array, and it will execute a remote command against them in parallel (as opposed to doing them one at a time). You can also use the -Session parameter if wanting to execute multiple commands against ongoing sessions.

Note: Keep in mind, that this is throttled to 32 concurrent connections at a time, by default. This can be modified via the -ThrottleLimit parameter.

To execute local functions against remote systems, you have to use a little trick:

# Let's say the function is called 'Do-Thing'$Computers = 'node1','node2'Invoke-Command -ComputerName $Computers -ScriptBlock ${function:Do-Thing} -ArgumentList 'arg1'

Though, it would likely be easier to simply save the functions/script into a file to be executed:

Invoke-Command -ComputerName $Computers -FilePath .\script.ps1

For further follow-up:

Update-Helphelp Invoke-Command -Fullhelp about_Remote

Checkout the following links if needed: