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

后端 未结 3 461
清歌不尽
清歌不尽 2021-01-18 05:32

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

相关标签:
3条回答
  • 2021-01-18 06:02

    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
    
    0 讨论(0)
  • 2021-01-18 06:03

    Resolve-Path will do the job, if path not found, will throw an error.

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

    0 讨论(0)
  • 2021-01-18 06:21

    try something like

    Test-Path $PathToFolder -ErrorAction SilentlyContinue
    

    then test and see if it's UnAuthorized

    $Error[0].Exception.GetType()
    
    0 讨论(0)
提交回复
热议问题