[IO.Directory]::GetDirectories and 'System Volume Information'

I’m writing a browser function for remote folders that gets the subfolder list recursively. The [IO.Directory]::GetDirectories() method stumbles upon protected folders like “System Volume Information” or “Documents and Settings” relusting in “Access is denied” error. Here’s a simplified example:

$Path = "\\SomeServerName\C$"
net use $path p@ssw0rd123 /user:SomeUserName
$DirList = [IO.Directory]::GetDirectories($Path)
Foreach ($Item in $DirList){
    Write-Host "Current item:" $Item
    #$ErrorActionPreference = 'SilentlyContinue'
    $SubDirList = [IO.Directory]::GetDirectories($Item)
    Write-Host "Subfolders:"
    $SubDirList
}

Of course I can wrap that operation in a try/catch block or suppress $ErrorActionPreference temporarily but that’s a kludge. How can I than distinguish if a “real” error occurs that needs user’s attention?

Is there a way to filter out these system folders in the first place?

Get-ChildItem -Directory -Hidden

The problem with Get-ChildItem is that it is painfully slow with UNC paths.

measure-command { get-childitem “\ServerName\C$\Windows\winsxs”}
Days : 0
Hours : 0
Minutes : 2
Seconds : 33
Milliseconds : 506
Ticks : 1535060499
TotalDays : 0,00177669039236111
TotalHours : 0,0426405694166667
TotalMinutes : 2,558434165
TotalSeconds : 153,5060499
TotalMilliseconds : 153506,0499

measure-command { [IO.Directory]::GetDirectories(“\ServerName\C$\Windows\winsxs”) }
Days : 0
Hours : 0
Minutes : 0
Seconds : 2
Milliseconds : 764
Ticks : 27641931
TotalDays : 3,19929756944444E-05
TotalHours : 0,000767831416666667
TotalMinutes : 0,046069885
TotalSeconds : 2,7641931
TotalMilliseconds : 2764,1931

That’s 2 minutes vs 2 seconds difference!

I wanted to recommend to determine the hidden folders and filter them. So you will only catch “real” errors.
Did you try

measure-command { get-childitem “\ServerName\C$\Windows\winsxs” -Directory -Hidden}