Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"
    }
} 

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading