Reputation: 113
I'm working on a script that has several functions that take time to execute on different remote computers. Is there any way I could Invoke-Command them in the same time in a parallel way? An example would be appreciated. Thanks
Upvotes: 4
Views: 9724
Reputation: 1080
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-Help
help Invoke-Command -Full
help about_Remote
Checkout the following links if needed:
Upvotes: 6