Garry Garry - 11 months ago 91
PowerShell Question

Using Powershell and Test-Path, how can I tell the difference between a "folder doesn't exist" and "access denied"

Using the Test-Path command in powershell, how can I tell the difference between a "folder doesn't exist" and "access denied"?


TL;DR: The good news is that Test-Path will often not return false even when you lack permissions (and when it doesn't, you'll get an exception instead of a simple $false)

In more depth, it depends on what you mean by access denied. Depending on what permissions you are looking to check, will depend on what PowerShell command will work for you.

As an example, a folder that non-administrators have no permissions for, such as C:\MSOCache if you have Microsoft Office installed. Test-Path returns true for this folder - it exists - even though you can't access it. On the other hand, running Get-Child-Item fails. So in this case, you would need to run

$path = 'C:\MSOCache'
if ((Test-Path $path) -eq $true)
    gci $path -ErrorAction SilentlyContinue
    if ($Error[0].Exception.GetType().Name -eq 'UnauthorizedAccessException')
        # your code here
        Write-Host "unable to access $path"

If however, you have read permissions but not write permissions, then you'll have to actually attempt to write to the file, or look at its security permissions and try to figure out what applies to the current user the script is running under:

(get-acl C:\windows\system32\drivers\etc\hosts).Access