Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can PowerShell trap errors in GetChildItem and continue looping?

I have a PowerShell script that is recursing down thru the file system using GetChildItem in a for-loop. As it travels, it is fixing ACL issues it finds (mostly where someone has blocked the BUILTIN\Administrators account)... but there are some it can't handle on it's own, like when I get [System.UnauthorizedAccessException] if there is an explicit "Deny" ACE.

The line of code looks like this:

foreach($file in Get-ChildItem $dirRoot -Recurse -ErrorAction Continue) {
    ...
}

When it stumbles on a path it can't read, it gives this exception:

Get-ChildItem : Access to the path 'C:\TEMP\denied' is denied. At Fix-ACLs.ps1:52 char:31 + foreach($file in Get-ChildItem <<<< $dirRoot -Recurse -ErrorAction Continue) { + CategoryInfo : PermissionDenied: (C:\TEMP\denied:String) [Get-ChildItem], Unauthorized AccessException + FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand

I would like to try/catch or trap the error so that I can repair the ACL (that is, remove the "Deny") in-place, and--most importantly--continue the loop without losing my place. Any suggestions for me?

like image 959
ewall Avatar asked Aug 04 '11 13:08

ewall


People also ask

What does trap do in PowerShell?

The trap keyword specifies a list of statements to run when a terminating error occurs. trap statements can handle the terminating errors in the following ways: Display the error after processing the trap statement block and continuing execution of the script or function containing the trap .

How to capture errors in PowerShell script?

Use the try block to define a section of a script in which you want PowerShell to monitor for errors. When an error occurs within the try block, the error is first saved to the $Error automatic variable. PowerShell then searches for a catch block to handle the error.

How can we handle error in PowerShell?

How to Code PowerShell Error Handling. There are three big steps to writing error handling in PowerShell: first is to identify where an error may occur: which command. Then, you put that command inside a try { } block. Third, you put inside a catch { } block what should be done if the error happens.


1 Answers

have you used silentlycontinue?

foreach($file in Get-ChildItem $dirRoot -Recurse -ErrorAction silentlycontinue) {
    ...
}
like image 89
Matt Avatar answered Nov 14 '22 22:11

Matt