test-path but with return codes

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.