powershell - 针对多个服务器运行脚本,但结果乱序

标签 powershell

因此,我使用 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/

相关文章:

azure - 如何连接到没有 PowerShell 订阅的 Azure AD 租户

powershell - Powershell:在html报告的顶部一次显示表头

windows - 我可以在 Windows 下向事件进程的 STDIN 发送一些文本吗?

maven - 使用Maven的Windows 10上的Docker

powershell - 在Powershell中使用UFormat转换时为什么会出现语法错误

powershell - Powershell ForEach循环间歇性工作-工作,失败,工作,失败,工作等

PowerShell 导入和排序 CSV 文件

PowerShell:创建本地用户帐户

powershell - 如何从目录中获取所有 powershell 脚本

powershell - 在 Powershell 中修改现有 CSV 文件