Powershell if file does not exist

Small gotcha that caught me recently, I needed to do a test-path but action if a file did NOT exist, and I had trouble getting it to work first go, so I’m writing this here:

$FileToCheck="c:\windows\system32\notepad.exe"
## check file exists
if (!(Test-Path $FileToCheck))
{
     throw "$FileToCheck not found"
}

This will throw the exception if the file can not be found.

Leave a Reply

Your email address will not be published. Required fields are marked *