PowerShell and catch exception

Posted on 2011-04-26
Medium Priority
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
  • 2
  • 2
LVL 12

Assisted Solution

rlandquist earned 2000 total points
ID: 35469652
For the catch try this code:
Catch [system.exception]
  "caught a system exception"

Open in new window


Author Comment

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

Accepted Solution

rlandquist earned 2000 total points
ID: 35469868
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

ID: 35469879
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

Prepare for your VMware VCP6-DCV exam.

Josh Coen and Jason Langer have prepared the latest edition of VCP study guide. Both authors have been working in the IT field for more than a decade, and both hold VMware certifications. This 163-page guide covers all 10 of the exam blueprint sections.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Auditing domain password hashes is a commonly overlooked but critical requirement to ensuring secure passwords practices are followed. Methods exist to extract hashes directly for a live domain however this article describes a process to extract u…
There are times when we need to generate a report on the inbox rules, where users have set up forwarding externally in their mailbox. In this article, I will be sharing a script I wrote to generate the report in CSV format.
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…
Loops Section Overview

840 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