Home > database >  Powershell redirect Get-Service to stderr when conection fails
Powershell redirect Get-Service to stderr when conection fails

Time:09-05

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.

CodePudding user response:

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
}
  • Related