PowerShell and catch exception

Hi,

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.
   Commands.GetChildItemCommand
 
ReneDKAsked:
Who is Participating?
 
rlandquistConnect With a Mentor Commented:
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

0
 
rlandquistConnect With a Mentor Commented:
For the catch try this code:
Catch [system.exception]
 {
  "caught a system exception"
 }

Open in new window

0
 
ReneDKAuthor Commented:
did you test that? because I already tried and it doesn't work for me...
0
 
ReneDKAuthor Commented:
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.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.