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.
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
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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
ASKER
Changing Write-Error to Write-Host completed your other changes to my script. Thanks very much
Try..
Open in new window