alphaleonis/AlphaFS

Powershell AlphaFS script stops when enumerating a file with insufficient permissions

Closed this issue ยท 6 comments

I'm enumerating files recursively and when a file is encountered where I don't have access to, the scripts stops:

foreach ($file in [Alphaleonis.Win32.Filesystem.Directory]::EnumerateFiles($fullPath,'*',[System.IO.SearchOption]::AllDirectories)){ #Code }

Can result in

(5) Access is denied: [\\?\UNC\some\random\path\*] At somescript.ps1 foreach ($file in [Alphaleonis.Wi ... ~~~~~ CategoryInfo : OperationStopped: (:) [], UnauthorizedAccessException FullyQualifiedErrorId : System.UnauthorizedAccessException

I also can't seem to trap the error with a simple try catch within the loop, as the issue is when enumerating $file. Doing it afterwards will cancel the loop anyway. Any ideas?

You need to add the: [Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions]::ContinueOnException enum member.

See how we do it here: Enumerate-FileSystemEntryInfos.ps1

Many thanks, I just don't really follow in the terminology. Can it be implemented in this line?

foreach ($file in [Alphaleonis.Win32.Filesystem.Directory]::EnumerateFiles($fullPath,'*',[System.IO.SearchOption]::AllDirectories)){ #Code }

From what I understand, Enumerate-FileSystemEntryInfos.ps1 generates a line of code which I tried to strip down with only having [Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions]::ContinueOnException added, but it stops searching after a couple of files. I have a break point in the script, but that shouldn't be the one stopping it as it didn't stop at ~2 scanned files before:

if($fileLastModified -ge $date){break}

I think this is what you need:

$dirEnumOptions = [Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions]::ContinueOnException
[Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions]$dirEnumOptions = $dirEnumOptions -bor [Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions]::Recursive

foreach ($file in [Alphaleonis.Win32.Filesystem.Directory]::EnumerateFiles($fullPath, $dirEnumOptions)) { 
    write-host $file
}

That did the trick! Where can I buy you a beer?

๐Ÿ‘ Enjoy an extra one for me!

FYI: Combining flag enum values can be made more readable by using the string parsing PS offers for enums. Something like:

$dirEnumOptions =
    [Alphaleonis.Win32.Filesystem.DirectoryEnumerationOptions] "ContinueOnException, Recursive"

That should at least help a little bit in constraining PS's sporadic tendency for overly verbose letter salads... ;)
Anyway, later i too will have a beer (or two) in your name, Yomodo! ๐Ÿ‘