Search code examples
.netpowershellfilepermission-deniedenumerate

Where to apply -ErrorAction on a .Net call?


This works to count *.jpg files.

PS C:\> @([System.IO.Directory]::EnumerateFiles('C:\Users\Public\Pictures', '*.jpg', 'AllDirectories')).Count
8

How can an -ErrorAction Continue be applied to this?

PS C:\> @([System.IO.Directory]::EnumerateFiles('C:\Users', '*.jpg', 'AllDirectories')).Count
An error occurred while enumerating through a collection: Access to the path 'C:\Users\Administrator' is denied..
At line:1 char:1
+ @([System.IO.Directory]::EnumerateFiles('C:\Users', '*.jpg', 'AllDire ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Solution

  • I don't think you can. Unless you want to implement directory traversal yourself you're probably stuck with something like this:

    Get-ChildItem 'C:\Users' -Filter '*.jpg' -Recurse -Force -ErrorAction SilentlyContinue