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

问题描述 投票:0回答:1

我有一个服务器和服务列表。我可以扫描服务器以获取服务列表并获取状态。我可以单独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 "}




    }
}

UPDATE

这样的东西可行,但由于某种原因,被击落的服务器会显示两次......

$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 "}

        }



        }
    }
powershell powershell-v2.0
1个回答
1
投票

我整理了你的代码,因为你为每个服务而不是每个服务器运行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,则主机会格式化输出以供显示。这发生在脚本的末尾。

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

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

如果我在我的Write-Host "$_ is online"Test-Connection线之间添加foreach,我得到:

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.