Finding Files plus Errors

by Oct 9, 2014

All PowerShell Versions

When you use Get-ChildItem to recursively search directory paths for files, you may stumble across subfolders where you do not have enough privileges. To suppress errors, you may use –ErrorAction SilentlyContinue.

That’s fine and good practice, but maybe you’d like to get a list of the folders that you actually had no access to, too.

Here is a script that searches for all PowerShell scripts within the Windows folder. It stores these files in $PSScripts. At the same time, it logs all errors in the variable $ErrorList and lists all folders that were inaccessible:

$PSScripts = Get-ChildItem -Path c:\windows -Filter *.ps1 -Recurse -ErrorAction SilentlyContinue -ErrorVariable ErrorList

$ErrorList | ForEach-Object {
  Write-Warning ('Access denied: ' + $_.CategoryInfo.TargetName)
} 

Twitter This Tip! ReTweet this Tip!