PowerShell测试连接,如果使用get-service存在服务

Mat*_*Moo 0 powershell if-statement

基本上我想查看文本文件中的计算机是否在线.如果他们不在线,则写主机"$ computer is down".如果$计算机在线,那么检查是否存在此服务,如果它存在则写入主机"$ computer installed,如果没有则写入主机"$ computer not installed".测试连接似乎有效但如果计算机在线他们都返回写主机"$ computer installed",即使我有一台我知道没有运行此服务的测试机器.

 function Get-RunService {

 $service = get-service -name ABCService

 Get-Content "C:\powershell\computers.txt" | 

  foreach {if (-not (Test-Connection -comp $_ -quiet))
  {
  Write-host "$_ is down" -ForegroundColor Red
  }
   if ($service ) 
   { 
    write-host "$_  Installed"
  }

else {

Write-host "$_  Not Installed"

}


 }

}

get-RunService
Run Code Online (Sandbox Code Playgroud)

Mat*_*att 5

看看这个清理过的代码版本.

function Get-RunService {

    Get-Content "C:\powershell\computers.txt" | 
        foreach {
            if (-not (Test-Connection -comp $_ -quiet)){
                Write-host "$_ is down" -ForegroundColor Red
            } Else {
                $service = get-service -name ABCService -ComputerName $_ -ErrorAction SilentlyContinue

                if ($service ){ 
                    write-host "$_  Installed"
                } else {
                    Write-host "$_  Not Installed"
                }
            }
        }
}

get-RunService
Run Code Online (Sandbox Code Playgroud)

我试图清理括号的工作方式.您检查主机是否还活着没有Else将服务器的可联系与服务器分开.旁注是ping可能会失败,但主机仍然可以存活,这一切都取决于您的环境,但要注意这种可能性.也移动了$service线路foreach添加-ComputerName $_

目前,您没有此错误的余地.该功能可能不存在,您应该考虑到这一点.最好的建议是要考虑-ErrorActionGet-Service一个try/catch块和可能.