因此,我使用 invoke-command 同时针对多个服务器运行脚本:
Invoke-Command -ComputerName $Servers -Credential $Cred -FilePath "C:\RemoteScript.ps1"
但是结果似乎不正常:
用户:用户名 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
我还想记录每个服务器的结果,但这就是我的想法:
Start-Process -FilePath Powershell -ArgumentList "
Invoke-Command -ComputerName $Server -Credential $Cred -FilePath "C:\RemoteScript.ps1"
" -RedirectStandardOutput "$Server Log.txt" -Wait
我应该如何能够在两台服务器上运行我的脚本,但应该尝试按顺序从每台服务器获取结果?
最佳答案
事实上,当使用 Invoke-Command
并行定位多台计算机时,无法保证跨计算机的输出对象的顺序。
您可以使用Group-Object
按(隐式添加的)PSComputerName
属性对输出对象进行分组,该属性反射(reflect)了源计算机:
Invoke-Command -ComputerName $Servers -Credential $Cred -FilePath C:\RemoteScript.ps1 |
Group-Object PSComputerName |
ForEach-Object { Set-Content "$($_.Name) Log.txt" -Value $_.Group }
请注意,Group-Object
隐式且始终输出按分组标准/a 排序的组,因此在本例中,组是按计算机名称排序的。
警告:在您的情况下,考虑到您将结果写入文件,无论如何您都不期望控制台输出,但如果您确实想看到相反,请注意,Group-Object
必须收集所有计算机上的所有输出,然后才能显示结果。
关于powershell - 针对多个服务器运行脚本,但结果乱序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73207765/