test-path but with return codes

Welcome Forums General PowerShell Q&A test-path but with return codes

This topic contains 0 replies, has 1 voice, and was last updated by  Forums Archives 7 years ago.

  • Author
  • #5305

    Points: 0
    Rank: Member

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

    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
    try {
    $Folder = Get-Item -Path $FolderPath -ErrorAction Stop -ErrorVariable GIError
    Catch [System.UnauthorizedAccessException]
    { Write-Host "Access Denied" }
    { $GIError.Exception }

    That may work for you.

The topic ‘test-path but with return codes’ is closed to new replies.