Using Powershell and Test-Path, how can I tell the difference between “folder does not exist” and “access is denied”,

Using the Test-Path command in powershell, how can I tell the difference between “folder does not exist” and “access denied”?

+4
source share
3 answers

TL DR: The good news is that it Test-Pathoften does not return false, even when you do not have enough permissions (and when not, you will get an exception instead of a simple one $false)

In more detail, it depends on what you mean by denying access. Depending on which permissions you want to check, it will depend on which PowerShell command works for you.

, , , C:\MSOCache, Microsoft Office. Test-Path true - ​​, . , Get-Child-Item .

$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"
    }
}

, , , , script :

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

-

Test-Path $PathToFolder -ErrorAction SilentlyContinue

$Error [0].Exception.GetType() , UnAuthorized

0

Resolve-Path will execute the task, if the path is not found, an error is issued.

https://technet.microsoft.com/en-us/library/hh849858.aspx

-1
source

All Articles