Search code examples
powershellpowershell-remoting

PowerShell 5.1 Get-Service array of computers and array of service names


PowerShell 5.1

I noticed when I use Get-Service with multiple computers and multiple service names that if a service name is not in one of the computers the execution fails, even if it exists in other computers listed. I've tried the following:

get-service -ComputerName $computers -Name $serviceNames -ErrorAction Continue

I'd like to list all services specified in computers specified. Some services may be on some of the computers but not all services exist on all computers.


Solution

  • The recommended way of doing it would be to not use Get-Service for remoting, use Invoke-Command instead. Do note that Get-Service in newer versions of PowerShell no longer supports remoting.

    $service = 'foo', 'bar', 'baz'
    Invoke-Command -ComputerName $computers { Get-Service $using:service }
    

    If you're limited by your remote hosts not having WinRM enabled / need to use DCOM as your remoting protocol, you could use Get-WmiObject with a constructed filter, this way, its not particularly pretty but it shouldn't throw when a service is not found in one of the remote hosts:

    $service = 'foo', 'bar', 'baz'
    $filter = $service | ForEach-Object { "name='$_'" }
    $filter = $filter -join ' OR '
    Get-WmiObject win32_service -Filter $filter -ComputerName $computers