Link to home
Start Free TrialLog in
Avatar of sekoon
sekoon

asked on

Help with Test-Path error handling

I am trying test create a couple of functions that will return the status of both the directory and file does or does not exist and if there is access to both.

First function shown below is testing if the folder and file exist and if the directory does not it is throwing an exception error that I need to catch nicely. If the directory does exist and the file does not the error message is never report which of course means the exception is not thrown which I currently don't have a try catch in place for it.

Help getting this script to execute catching the error and returning the correct pass or fail message would be appreciated.


Function TestExist()
{
    if (!(Test-Path $TestDir -pathType "Container"))
	    {
            $errMsg = "*** Error: File Directory: " + $TestDir + " does not exist. "
		    Write-Error $errMsg
	    }
    else
        {
            if (!(Test-Path $TestFileFQDN))
	        {
                $errMsg = "*** Error: File: " + $TestFile + " does not exist. "
		        Write-Error $errMsg
	        }
        }
}


Clear-Host

$TestDir = "c:\temp"
$TestFile = "testfile.txt"


TestExist

Open in new window

Avatar of SubSun
SubSun
Flag of India image

In your code you didnt define $TestFileFQDN ...

Try..

$TestDir = "c:\temp"
$TestFile = "testfile.txt"
$TestFileFQDN = "$TestDir\$TestFile"

TestExist

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of SubSun
SubSun
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of sekoon
sekoon

ASKER

Works like a charm until I hand it an invalid directory or file than it throws me a WriteException error. How can I trap the exception error so that what is return is directory or file does not exist with possibly the Exception Error
If there is an invalid directory then the script will generate error.. That's how it's written.. is that what you want? If not please explain..
If you are just trying to display the error message then use Write-Host or Write-Output instead of Write-Error
Avatar of sekoon

ASKER

Changing Write-Error to Write-Host completed your other changes to my script. Thanks very much