test-path but with return codes

This topic contains 0 replies, has 1 voice, and was last updated by Profile photo of Forums Archives Forums Archives 5 years, 5 months ago.

  • Author
    Posts
  • #5305

    by Lembasts at 2012-11-25 19:46:05

    Greetings,
    If I use test-path to check for the existance of a folder, in some circumstances I get False.
    Thats all well and good, but I know that in some cases the folder doesnt exist and in other cases the folder exists but I dont have permissions to get to it.
    I need to be able to find out which one it is when False is returned.

    by coderaven at 2012-11-25 21:51:11

    From what it sounds like, you want to know if the test-path failed just because of access denied. If that is the case, if the test-path returns false run some more test.

    Use a try .. catch block and try to access the path and check your exception

    if (Test-Path -Path $FolderPath)
    {
    #found it continue
    }
    else
    {
    try {
    $Folder = Get-Item -Path $FolderPath -ErrorAction Stop -ErrorVariable GIError
    }
    Catch [System.UnauthorizedAccessException]
    { Write-Host "Access Denied" }
    Catch
    { $GIError.Exception }
    }

    That may work for you.

You must be logged in to reply to this topic.