如何正确地 ping 和扫描计算机上的服务,然后转到列表中的下一台计算机?

How to properly ping and scan services on computer, then move on to next computer in list?

我有一个服务器和服务列表。我可以扫描服务器以获取服务列表并获取状态。我可以单独 ping 服务器列表以查看它们是否正常运行。

我在组合 2 时遇到问题。我想 ping 列表中的服务器,然后扫描该服务器以查找我列出的所有服务。显示所有服务的状态。然后移动到列表中的下一个服务器执行相同的操作。

我只想将它们组合在一起,以便当前服务器的 ping 与该服务器的服务扫描一起显示。

关于如何正确执行此操作的任何建议?

$serviceList = gc C:\services.txt

get-content C:\servers.txt | % {
ForEach ($service in $serviceList)
{




    if (Test-Connection -computer $_ -BufferSize 16 -Count 1 -ea 0 -quiet) {
        Write-Host $_ is online
    }
    else {"$_ is offline"}





    if ($s=get-service -computer $_ -name $service -ErrorAction SilentlyContinue)
    {
        $s | select MachineName, ServiceName, Status, StartType
    }
    else {"$_ $service "}




    }
}

更新

像这样的东西可以工作,但由于某种原因,关闭的服务器显示两次...

$serviceList = gc C:\services.txt   # gc is short for Get-Content



    get-content C:\servers.txt | % {
    ForEach ($service in $serviceList)
    {


        if (-not (Test-Connection -computer $_ -BufferSize 16 -Count 1 -ea 0 -quiet)) {
            Write-Host "$_ is offline" -ForegroundColor Red
        }

        else {

        if ($s=get-service -computer $_ -name $service -ErrorAction SilentlyContinue)
        {
            $s | select MachineName, ServiceName, Status, StartType
        }
        else {"$_ $service "}

        }



        }
    }

我稍微整理了一下你的代码,因为你是 运行 Test-Connection 每个 服务 而不是每个服务器:

$serviceList = Get-Content C:\work\services.txt

Get-Content C:\work\servers.txt | ForEach-Object {
    if (Test-Connection -ComputerName $_ -BufferSize 16 -Count 1 -EA 0 -Quiet) {
        foreach ($service in $serviceList) {
            if ($s=get-service -computer $_ -name $service -ErrorAction SilentlyContinue)
            {
                $s | select MachineName, ServiceName, Status, StartType
            } else {
                "$_ $service "
            }
        }
    } else {
        "$_ is offline"
    }
}

但我认为这不是您的根本问题。我认为问题在于您混淆了输出数据的方式。例如,我上面写的是:

MachineName  ServiceName  Status StartType
-----------  -----------  ------ ---------
bob1         RpcLocator  Stopped    Manual
bob1         SENS        Running Automatic
dave2 is offline

(这与机器在服务器文件中出现的顺序相同)。您在一个地方使用 Write-Host 而在另一个地方使用(双)引号。使用引号等同于使用 Write-Output。 Write-Output 将数据粘贴到管道中,以供下一个 cmdlet 处理。如果没有下一个 cmdlet,主机会格式化输出以供显示。这发生在脚本的末尾。

如果我对最后一个 else 使用 Write-Host,输出将变为:

 dave2 is offline
 MachineName  ServiceName  Status StartType
 -----------  -----------  ------ ---------
 bob1         RpcLocator  Stopped    Manual
 bob1         SENS        Running Automatic

如果我在 Test-Connectionforeach 行之间添加 Write-Host "$_ is online",我得到:

 bob1 is online
 dave2 is offline
 MachineName  ServiceName  Status StartType
 -----------  -----------  ------ ---------
 bob1         RpcLocator  Stopped    Manual
 bob1         SENS        Running Automatic

如果您在脚本末尾添加 Write-Host '-',您会看到服务数据出现在该脚本的末尾。

最简单的解决办法就是坚持使用一种输出方式。