Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

powershell

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

like image 448
Garry Avatar asked Feb 18 '15 16:02

Garry


2 Answers

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
like image 82
NextInLine Avatar answered Oct 21 '22 18:10

NextInLine


try something like

Test-Path $PathToFolder -ErrorAction SilentlyContinue

then test and see if it's UnAuthorized

$Error[0].Exception.GetType()
like image 1
Sean Rhone Avatar answered Oct 21 '22 18:10

Sean Rhone