Hi, hope you can help. I want to capture a list of folder/file paths to a CSV where PS generates a ReadError when run by the local\administtrator. I have this script but it fails, well, because PS has a ReadError
The error is being generated by Get-ChildItem, so you’ll need to try/catch that command as well. The error message shows network error, not necessarily a permission issue. Depending on how many folders you’re working with, += may be a huge slowdown. It creates another new array each time you use that. Finally, not all errors are terminating and thus won’t be “caught” so make sure to either set erroraction to stop per cmdlet or set $erroractionpreference to stop at the beginning for all cmdlets.
# Makes all errors terminating errors
$ErrorActionPreference = 'Stop'
$rootFolderPath = Get-Content "C:\\script\pathlist.txt"
$csvFilePath = "C:\script\error.csv"
$folderreaderrorlist = New-Object System.Collections.Generic.List[string]
$aclreaderrorlist = New-Object System.Collections.Generic.List[string]
# Recursively iterate through folders and check permissions
# Not only is it easier to read and maintain, but breaking up commands like this can be much faster than piping into loops
$directorylist = try{
Get-ChildItem -Path $rootFolderPath -Recurse -Directory
}
catch{
$folderreaderrorlist.Add($_.Exception.Message)
}
# Instead of creating a new variable inside a ForEach-Object loop, just use a foreach loop
foreach($folderpath in $directorylist.FullName){
# Attempt to retrieve the folder's permissions
try {
$acl = Get-Acl -Path $folderPath
$permissions = $acl.Access | Select-Object -ExpandProperty IdentityReference
} catch {
# PowerShell doesn't have permissions to access the folder
$aclreaderrorlist.Add($folderPath)
}
}
# Export the paths to a CSV file
$aclreaderrorlist | Export-Csv -Path $csvFilePath -NoTypeInformation
# errors reading directories are stored in
$folderreaderrorlist
Write-Host "Folder paths without PowerShell permissions logged to $csvFilePath."
Thanks very much for your comprehensive reply and suggestions.
I’ve run your amended script against some test files. It runs through without error but doesn’t seem to report back on the folders where it doesn’t have permissions.
An “unexpected network error” could be a lot of things and most if not all are likely to be network related and not specifically powershell. You may want to try accessing the location without powershell and with wireshark running to capture the interaction.