I’m trying to trap errors using a try/catch block with Get-Childitem but it isn’t working. Here is an excerpt of my code:
if((Test-Path .test.txt)){
$key = Get-Content -Path .test.txt
} else {
write-host "test.txt file not found in current folder. Searching for it in other folders." -ForegroundColor DarkCyan
try {
$key = @(gci -path $env:USERPROFILE -file test.txt -Recurse -ErrorVariable ers )[0]
} catch [System.UnauthorizedAccessException]{
write-warning -Message "Folder offlimits"
} catch [RuntimeException]{
write-warning -Message "Some other error occured"
} finally {
write-host $key.FullName
}
}
I know I can just use -erroraction silentlycontinue but I’m really just trying to figure out how to trap the error. I tried using $error[0].Exception.gettype().fullname to determine what the error was to trap it but I used what it returned and it didn’t trap it. I don’t want to use -filter or -include/exclude because there are just too many of them.
and $ers is:
gci : Access to the path 'C:UserSearchData' is denied.
At line:6 char:26
+ ... $key = @(gci -path $env:USERPROFILE -file test.txt -Recurse -Error ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (C:UserSearchData:String) [Get-ChildItem], UnauthorizedAccessException
+ FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand
which is the same thing $error[0] contains. I’m using 5.6.1 right now but I’m transitioning to 7. This is on Windows 10 if that matters. I’m stumped. Any thoughts?