Search code examples
powershellstderrio-redirection

Powershell redirect Get-Service to stderr when conection fails


After:

$services = Get-Service -ComputerName $server 2>$null

The stderr isn't redirected to $null and the error message is printed when conection fails or not enought permissions.


Solution

  • Use a try/catch statement to capture (and suppress) the exception:

    try {
        $services = Get-Service -ComputerName $server -ErrorAction Stop
        # do stuff with $services here
    }
    catch [InvalidOperationException] {
        # we'll ignore these
    }