运行powershell命令以检查远程服务器服务的状态的问题

时间:2018-04-12 00:19:29

标签: powershell service windows-scripting

标题非常自我解释,我在针对服务器和服务列表运行以下脚本时遇到问题。当我运行它时,我总是遇到以下错误,即使我在ex01上运行get-service时,我也可以看到服务及其状态。不确定断开连接的位置,但感谢任何帮助。

Get-Service : Cannot find any service with service name 'MsExchangeIS'.

在\ dc01 \ c $ \ DriveMan \ ServiceStatusCHK \ Srvstatuscheck.ps1:12 char:31 + $ service_status =(Get-Service -Name $ service).Status + ~~~~~~~~~~~~~~~~~~~~~~~~~~     + CategoryInfo:ObjectNotFound:(MsExchangeIS:String)[Get-Service],ServiceCommandException     + FullyQualifiedErrorId:NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.GetServiceCommand

$ErrorActionPreference= 'continue'
$services = ("dns","dhcp","MsExchangeIS")
$servers  = 'dc01','dc02','ex01','ex02'


foreach($server in $servers){

$service_status = (Get-Service -Name $service).Status

    foreach($service in $services){

       #start-sleep -s 1



       if((((Get-Service -Name $service).status) -eq 'running')){

           "$service on $server is Running" | write-host -foregroundcolor green 

                } else  

                {"$service on $server is DOWN" | write-host -foregroundcolor red 

                } }}         

            pause   

1 个答案:

答案 0 :(得分:1)

您正在检查本地计算机上的服务,而不是远程计算机。

Get-Service -Name $service

应该是

Get-WmiObject win32_service -computername $server -filter "name='$Service'"

但是,您可以在没有循环的情况下执行此操作,因为Get-WMIObject可以使用远程计算机的集合和过滤器来指定多个服务。

$ErrorActionPreference= 'continue'
$services = ("dns","dhcp","MsExchangeIS")
$servers  = 'dc01','dc02','ex01','ex02'
$filter = "";
foreach ($svc in $services) {
    $filter += "name = '$svc' or ";
}
$filter = $filter.Substring(0,$filter.Length-4);
Get-WmiObject -Class win32_service -filter $filter -ComputerName $servers|select-object -property pscomputername,name,state | format-table -autofit;