Check with powershell if service is installed on m

2019-09-11 00:41发布

I'm looking for help with my script again :)

I have a script that will query list of servers to find if specific service is installed. This works fine. However, I know that there are some servers in my list that I don't have access to, or there are different credentials. How do I make this visible in output? Because I only get output that service is not installed, which is not true, I just don't have correct credentials.

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

Also, I'd like to have output formatted into the one line, e.g.:

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

Thanks a lot for any help.

2条回答
甜甜的少女心
2楼-- · 2019-09-11 01:27

Here's an option which just displays the content of the error on failure:

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
}

As for the second part of the question @arco444 has described the correct approach.

查看更多
Emotional °昔
3楼-- · 2019-09-11 01:39

Here's a WMI solution. Any errors you get from attempting to connect to remote computers will be caught with the try/catch blocks. The result of each operation will be stored to a custom object and added to the array that holds the results of all the operations.

$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

You should end up with something like this:

server state
------ -----
s1     running
s4     stopped
s2     The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
查看更多
登录 后发表回答