1
votes

I have code that reliably generates an exception. This is expected so I don't want it to show up at the end of my script when I dump the $error variable to look for actual problems.

Well step 1 is to find this exception and handle it, right? I can't get that far. Here is what I've got:

Function Add-PowerShellSnapIn($SnapInName){
    Try{
        if ((Get-PSSnapin -Name $SnapInName) -eq $null){
            Write-Warning "SnapIn Is Not Already Loaded"
        }
    }Catch [System.Exception]{
        Write-Warning "Error Caught"
    }
}

Add-PowerShellSnapIn -SnapInName "Microsoft.Exchange.Management.PowerShell.Admin"

If I run this code I can see the exception, but I never see my little "Write-Warning" test message to indicate that the Catch block caught the exception. I must be missing something here. Here is the exception I see:

Get-PSSnapin : No Windows PowerShell snap-ins matching the pattern 'Microsoft.Exchange.Management.PowerShell.Admin' were found. Check the pattern and then try the command again. At C:\users\myuser\Desktop\Test.ps1:4 char:20 + if ((Get-PSSnapin <<<< -Name $SnapInName) -eq $null){ + CategoryInfo : InvalidArgument: (Microsoft.Excha...owerShell.Admin:String) [Get-PSSnapin], PSArgumentException + FullyQualifiedErrorId : NoPSSnapInsFound,Microsoft.PowerShell.Commands.GetPSSnapinCommand

Edit: Thanks in advance for anyone who takes the time to help me out!

1

1 Answers

6
votes

You should add -ErrorAction stop to your Get-PSSnapin to get into the Catch Block.

Function Add-PowerShellSnapIn($SnapInName){
    Try{
        if ((Get-PSSnapin -Name $SnapInName -ErrorAction Stop) -eq $null){
            Write-Warning "SnapIn Is Not Already Loaded"
        }
    }Catch [System.Exception]{
        Write-Warning "Error Caught"
    }
}

Add-PowerShellSnapIn -SnapInName "Microsoft.Exchange.Management.PowerShell.Admin"