Home > OS >  Try Catch does not work with multiple catches (PowerShell)
Try Catch does not work with multiple catches (PowerShell)

Time:08-25

Right now im working on a small GUI based PowerShellscript, where i want to use multiple catcehs to catch all relevant errors.

The problem I have is: if i use only one catch, the error gets recognized as it should. If i use multiple catches i still get the errors in the console which makes no sense to me.

Here are two pictures:

Here with one catch{} i won't get a error

1

Here with multiple catches i get the error even if i set a catch for this specific error

2

I hope someone can help.

The code is:

$buttonShares.Add_Click(
{
    $listBoxItem = $listBoxGroup.SelectedItem.ToString().Trim()

    $path = "\\kpd-srv-10\$listBoxItem"

    $acl = @{}

    $listBoxShares.Items.Clear()

    try
    {
        $acl = Get-Acl -Path $path

        $listBoxShares.Items.Clear()
    }
    catch [System.UnauthorizedAccessException]
    {
        $listBoxShares.Items.Add("keine Berechtigung")
    }
    catch [System.ItemNotFoundException]
    {
        $listBoxShares.Items.Add("Laufwerk konnte nicht gefunden werden")
    }
    catch
    {
        $listBoxShares.Items.Add("Es ist ein Fehler aufgetreten!")
    }

    foreach ($Access in $acl.Access)
    {
        if($Access.IdentityReference -notlike "PBL*")
        {
            continue
        }
        
        $listBoxShares.Items.Add($Access.IdentityReference)
    }
}) 

CodePudding user response:

Why not just use the existing error messages?

Try {
    $acl = Get-Acl -Path $path -ErrorAction Stop
    $listBoxShares.Items.Clear()
}
Catch {
    $ErrType = $_.Exception.Message
    $listBoxShares.Items.Add($ErrType)
}

CodePudding user response:

As commenter notjustme noted, you got the second exception type wrong. It should be [System.Management.Automation.ItemNotFoundException].

To confirm that, I wrote $_.Exception.GetType().FullName in a single untyped catch {} block, which outputs the full exception name.

Demo (to be run without admin privileges):

$ErrorActionPreference = 'Stop'

Function Test-MyException( [scriptblock] $ScriptBlock ) {
    try 
    {
        & $ScriptBlock
    }
    catch [System.UnauthorizedAccessException]
    {
        "keine Berechtigung"
    }
    catch [System.Management.Automation.ItemNotFoundException]
    {
        "Laufwerk konnte nicht gefunden werden"
    }
    catch
    {
        "Es ist ein Fehler aufgetreten!"
    }
}

Test-MyException { Get-Content notfound }
Test-MyException { New-Item $env:SystemRoot\foobar.txt }
Test-MyException { throw 'another error' }

Output:

Laufwerk konnte nicht gefunden werden
keine Berechtigung
Es ist ein Fehler aufgetreten!
  • Related