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.
For example, C:\System Volume Information is a folder that non-administrators have no permissions for. 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:\System Volume Information'
if ((Test-Path $path) -eq $true)
{
gci $path -ErrorAction SilentlyContinue
if ($Error[0].Exception -is [System.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
Resolve-Path
will do the job, if path not found, will throw an error.
https://technet.microsoft.com/en-us/library/hh849858.aspx
try something like
Test-Path $PathToFolder -ErrorAction SilentlyContinue
then test and see if it's UnAuthorized
$Error[0].Exception.GetType()