如果多台计算机上安装了服务,请检查powershell

时间:2014-11-25 09:39:52

标签: powershell service

我正在寻找有关我的脚本的帮助:)

我有一个脚本,它将查询服务器列表以查找是否安装了特定服务。这很好用。但是,我知道我的列表中有一些我无法访问的服务器,或者有不同的凭据。如何在输出中显示它?因为我只获得未安装服务的输出,这不是真的,我只是没有正确的凭据。

$name = "BESClient"
$servers = Get-content C:\list.txt

function Confirm-WindowsServiceExists($name)
{   
   if (Get-Service -Name $name -Computername $server -ErrorAction Continue)
   {
       Write-Host "$name Exists on $server"
       return $true
   }
       Write-Host "$name does not exist on $server"
       return $false
}

ForEach ($server in $servers) {Confirm-WindowsServiceExists($name)}

另外,我希望将输出格式化为一行,例如:

Server1        Service running
Server2        Service not installed
Server3        no access
etc...

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

这是一个WMI解决方案。尝试连接到远程计算机时遇到的任何错误都将通过try / catch块捕获。每个操作的结果将存储到一个自定义对象,并添加到包含所有操作结果的数组中。

$result = @()

$name = "BESClient"
$servers = Get-Content C:\list.txt
$cred = Get-Credential

foreach($server in $servers) {
  Try {
    $s = gwmi win32_service -computername $server -credential $cred -ErrorAction Stop | ? { $_.name -eq $name }
    $o = New-Object PSObject -Property @{ server=$server; status=$s.state }
    $result += ,$o
  }
  Catch {
    $o = New-Object PSObject -Property @{ server=$server; status=$_.Exception.message }
    $result += ,$o
  }
}

$result | Format-Table -AutoSize

你应该得到这样的东西:

server state
------ -----
s1     running
s4     stopped
s2     The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

答案 1 :(得分:2)

这是一个只显示失败时错误内容的选项:

function Confirm-WindowsServiceExists($name)
{   
   if (Get-Service -Name $name -Computername $server -ErrorAction SilentlyContinue -ErrorVariable WindowsServiceExistsError)
   {
       Write-Host "$name Exists on $server"
       return $true
   }

   if ($WindowsServiceExistsError)
   {
       Write-Host "$server" $WindowsServiceExistsError[0].exception.message
   }

   return $false
}

至于问题的第二部分@ arco444描述了正确的方法。