0

I have found an answer on how to check whether the current user has read permissions on a file with powershell.

How can I do a similar check for directories? (Without having to install additional modules.)

Zulakis
  • 7,859
  • 10
  • 42
  • 67

1 Answers1

3

Don't bother with checking access control lists.

The proper way to check if you have read permissions on any object is plain and simple. Try to read it, and catch the "access denied" error.

try {
    Get-ChildItem "path\to\that\directory" -ErrorAction Stop
} catch [System.UnauthorizedAccessException] {
    Write-Host "$($_.TargetObject): Access denied"
} catch [System.Management.Automation.ItemNotFoundException] {
    Write-Host "$($_.TargetObject): Path not found"
}
Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • Trying this with a UNC-Path leads to an `unexpected network error` exception, but only on the first call. Any idea on how to fix this? – Zulakis Dec 19 '21 at 13:47
  • "UNC path" or "local path" are the same as far as `Get-ChildItem` is concerned, which means either it works, or you get "Access Denied"/"File not found". "Unexpected network error" sounds unrelated, I can't recommend more than googling the error message. – Tomalak Dec 19 '21 at 14:39
  • @Zulakis I've tested some more and I always get `Access is denied` immediately on UNC paths I am not allowed to read. Not sure what causes your "unexpected network error", but the UNC path is not it. – Tomalak Dec 20 '21 at 18:03