【问题标题】:Issues running powershell command to check status of remote servers services运行 powershell 命令以检查远程服务器服务状态的问题
【发布时间】:2018-04-12 00:19:28
【问题描述】:

标题是不言自明的,我在针对服务器和服务列表运行以下脚本时遇到问题。即使我在 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   

【问题讨论】:

    标签: powershell service windows-scripting


    【解决方案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;
    

    【讨论】:

    • 如何根据我定义的服务是否正在运行为输出着色?
    • 你不能用format-table。您必须遍历 get-wmiservice 返回的每个项目,测试并使用 write-output
    猜你喜欢
    • 1970-01-01
    • 2019-01-13
    • 1970-01-01
    • 1970-01-01
    • 2014-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多