The behavior you're seeing is by design. When you call [System.IO.Directory]::EnumerateDirectories(), the enumeration is lazy. That means the underlying API starts returning results and only throws an exception when it first encounters a directory it can't access. It doesn't aggregate multiple exceptions—it simply throws the first one it hits.
If you want to process as many entries as possible (and handle exceptions individually), you'll need to wrap your enumeration logic in a try/catch block for each directory access. For example, you could use a recursive method that catches exceptions at each level.
Here's a simple example in PowerShell to illustrate the idea:
function Get-AllDirectories {
param (
[string]$Root
)
$directories = @()
try {
# This is a lazy enumerable.
$subDirs = [System.IO.Directory]::EnumerateDirectories($Root)
}
catch {
Write-Warning "Access denied or error accessing $Root: $_"
return
}
foreach ($dir in $subDirs) {
$directories += $dir
# Recursively process subdirectories
$directories += Get-AllDirectories -Root $dir
}
return $directories
}
# Usage
Get-AllDirectories -Root "C:\Your\Path"
In this example, if an UnauthorizedAccessException occurs when trying to enumerate a specific directory, it is caught and a warning is issued. This way, you avoid halting the entire operation when one directory is inaccessible.
So, to summarize: you're not doing anything wrong, and it's not a bug—the method only throws the first exception encountered because of its lazy iterator design.