Get the class of an exception and catch it

This topic contains 3 replies, has 2 voices, and was last updated by Profile photo of Dave Wyatt Dave Wyatt 7 months, 2 weeks ago.

Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #35157
    Profile photo of Paal Braathen
    Paal Braathen
    Participant

    Hi

    I want to catch only a specific error that is thrown. The problem is that i don't know it's class.

    How can I display the full class name of my exception when it's thrown?

    Example code (including a question). As you see I'm trying to get events from the future. This will throw NoMatchingEventsFound. I want to catch this and only this error.

    $LogName = "Application"
    
    try {
        Get-WinEvent -FilterHashtable @{"LogName" = $LogName; "StartDate" = (Get-Date -Year 2020)} -ErrorAction "Stop"
    } catch {
        $_ # And why can't this be piped to Format-List?
    }
    #35158
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    Exceptions and ErrorRecords, for whatever reason, need to have the -Force switch used when you pipe them to Format-List and such. I forget why that is, but PowerShell really really wants to display them the way it thinks they should be displayed. 🙂

    To get the type of the exception, $_.Exception.GetType().FullName should suffice.

    #35262
    Profile photo of Paal Braathen
    Paal Braathen
    Participant

    @dlwyatt

    $_.Exception.GetType().FullName only gives me System.Exception. Is that really the class of the error?

    #35265
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    That would be very unusual, but not impossible. .NET code (including PowerShell cmdlets) generally considers it a bad practice to just throw the base exception class, rather than subclassing it to something more useful that can be caught and handled specifically.

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.