Home > OS >  Running a script against multiple servers, but the outcome is out of order
Running a script against multiple servers, but the outcome is out of order

Time:08-03

So, I'm using invoke-command to run a script against more than one server simultaneously:

Invoke-Command -ComputerName $Servers -Credential $Cred -FilePath "C:\RemoteScript.ps1"

However the results appear to be out of order:

User: username FQDN: DEVSERVER01.localnet.int IP: 10.0.0.101

Server uptime: 20 days
======================

User: username
FQDN: DEVSERVER02.localnet.int
IP: 10.0.0.202

Server uptime: 20 days
======================

User: username
FQDN: DEVSERVER03.localnet.int
IP: 10.0.0.303

Server uptime: 20 days
======================

List of updates for DEVSERVER01.localnet.int:
No updates

List of updates for DEVSERVER02.localnet.int:
No updates

List of updates for DEVSERVER03.localnet.int:
No updates

I also want to log the results for each server but this is what I came up with:

Start-Process -FilePath Powershell -ArgumentList "
    Invoke-Command -ComputerName $Server -Credential $Cred -FilePath "C:\RemoteScript.ps1"
" -RedirectStandardOutput "$Server Log.txt" -Wait

How should I be able to run my script on two servers but should try to get the results from each server in order?

CodePudding user response:

Indeed, when targeting multiple computers in parallel with Invoke-Command, the order of the output objects across computers is not guaranteed.

You can use Group-Object to group the output objects by their (implicitly added) PSComputerName property, which reflects the computer of origin:

Invoke-Command -ComputerName $Servers -Credential $Cred -FilePath C:\RemoteScript.ps1 |
  Group-Object PSComputerName |
  ForEach-Object { Set-Content "$($_.Name) Log.txt" -Value $_.Group }

Note that Group-Object implicitly and invariably outputs the groups sorted by the grouping criterion/a, so that the groups are sorted by computer name in this case.

Caveat: In your case, given that you're writing the results to files, you have no expectation of console output anyway, but if you do want to see the results in the console instead, note that Group-Object has to collect all output, across all computers, before it can display the results.

  • Related