Search code examples
powershellpowershell-remoting

How can I make any errors thrown go thru the else part of my condition?


Given: PowerShell 5.1

I'm getting an "Access denied" for some of the the computers in the array. How can make any errors run through the "else" part of condition where it's NOT running? Right now, it's just throwing entire error message and I don't want the user to see all that.

Invoke-Command -ComputerName $computers {
    $rstest = Get-Service -Name MyService1
    
    if ($rstest.Status -eq 'Running') {
        "Service $($rstest.Name) is running"
    }
    else{
        "Service $($rstest.Name) is NOT running"
    }
} 

Solution

  • "Access Denied" errors aren't due to Get-Service, if the service wasn't there you would be getting a different error, i.e.: "Cannot find any service with service name...". These are because you can't connect to the remote computers either due to lack of permissions or perhaps the servers don't have PSRemoting enabled.

    Easiest way to handle this is probably using -ErrorAction SilentlyContinue on your Invoke-Command statement together with -ErrorVariable and then checking if the error variable is populated:

    Invoke-Command -ComputerName $computers {
        $rstest = Get-Service -Name MyService1
    
        if ($rstest.Status -eq 'Running') {
            "Service $($rstest.Name) is running"
        }
        else {
            "Service $($rstest.Name) is NOT running"
        }
    } -ErrorAction SilentlyContinue -ErrorVariable errors
    
    if ($errors) {
        # here you can find the computers that you couldn't connect to
        $errors.TargetObject
    }