I tweaked my code since there’s no since in checking for additional services if the first attempt fails.
[pre] function Get-MrService { [CmdletBinding()] param ( [ValidateNotNullOrEmpty()] [string[]]$ComputerName = ('s1','s2','s3'), [ValidateNotNullOrEmpty()] [string[]]$ServiceName = 'bits' ) foreach ($Computer in $ComputerName) { $reachable = $true foreach ($Service in $ServiceName) { if ($reachable) { $ServiceInfo = Get-Service -Name $Service -ComputerName $Computer -ErrorAction SilentlyContinue } if (-not($ServiceInfo) -or (-not($reachable))) { $ServiceInfo = @{ MachineName = $Computer Name = $Service Status = 'Unreachable' } $reachable = $false } [PSCustomObject]@{ ComputerName = $ServiceInfo.MachineName Name = $ServiceInfo.Name Status = $ServiceInfo.Status } } } }
[/pre]
All of this code is slow though. If PowerShell remoting is enabled on the remote machines, consider talking advantage of it instead of using the ComputerName parameter of Get-Service since using Invoke-Command would cause this to be done in parallel against the remote machines and it would be a lot less likely to be blocked by a firewall.