PowerShell and catch exception

Posted on 2011-04-26
Last Modified: 2012-05-11

this pretty simple piece of code is causing me a problem.

Why doesn't it catch the UnauthorizedAccessException

 try{ Get-ChildItem <path to folder with no access>}
catch{ "exception" }

I get the following error output:
Get-ChildItem : Access to the path '<path to folder with no access>' is denied
At line:1 char:19
+ try{ Get-ChildItem <<<<  <path to folder with no access>}catch{ "exception"
    + CategoryInfo          : PermissionDenied: (<path to folder with no access>:String) [Get-ChildItem], UnauthorizedAccessException
    + FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.
Question by:ReneDK
    LVL 12

    Assisted Solution

    For the catch try this code:
    Catch [system.exception]
      "caught a system exception"

    Open in new window


    Author Comment

    did you test that? because I already tried and it doesn't work for me...
    LVL 12

    Accepted Solution

    I found out the issue.  The error is being generated by the Get-ChildItem before it gets to the catch.  To fix this use the following code:
    try{ Get-ChildItem <path to folder with no access> -ErrorAction Stop}
    catch [System.Exception]
    { "exception" }

    Open in new window


    Author Comment

    Aaah... As I tried to hide the error output temporarily I added ErrorAction AND and the same time remove the try/catch. Didn't realize they had to be combined. Thanks a lot.

    Featured Post

    Do You Know the 4 Main Threat Actor Types?

    Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

    Join & Write a Comment

    This article shows how a content item can be identified directly or through translation of a navigation type. It then shows how this information can be used to create a menu for further navigation.
    Are you one of those front-line IT Service Desk staff fielding calls, replying to emails, all-the-while working to resolve end-user technological nightmares? I am! That's why I have put together this brief overview of tools and techniques I use in o…
    This video discusses moving either the default database or any database to a new volume.
    This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor ( If you're looking for how to monitor bandwidth using netflow or packet s…

    754 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    19 Experts available now in Live!

    Get 1:1 Help Now