Behind the PowerShell Pipeline logo

Behind the PowerShell Pipeline

Subscribe
Archives
July 20, 2023

Catch Them All PowerShell

Welcome back. Last time we started looking at how to use Try/Catch in your PowerShell scripts to handle errors better. And you want to handle them. As a best practice, do not “eat” exceptions.

$svcs = 'bits', 'oops', 'winrm', 'foo', 'winmgmt'
foreach ($s in $svcs) {
    Try {
        Get-Service $s -ErrorAction Stop
    }
    Catch { }
}

If there are errors, you will never see them. If you write a Try/Catch block, the assumption is that you want to handle the error. If you truly don’t care about exceptions, then ignore them.

Get-Service $svcs -ErrorAction SilentlyContinue
Get-Service $svcs -ErrorAction Ignore
Want to read the full issue?
GitHub Bluesky LinkedIn About Jeff
Powered by Buttondown, the easiest way to start and grow your newsletter.