Export (0) Print
Expand All

Verifying That a File Exists

Microsoft® Windows® 2000 Scripting Guide

Sometimes it is important simply to know whether a file exists. This might be done as part of a software inventory; for example, you might want to check all your mail servers and see whether a particular script file is present.

Knowing whether a file exists is also important when using scripts to carry out file system management tasks; as you might expect, attempting to copy, move, delete, or otherwise manipulate a file that does not exist will generate a run-time error. To avoid this kind of error, you can use the FileExists method to verify the existence of the file. The FileExists method requires a single parameter (the path to the file) and returns a Boolean value: True if the file exists; False if it does not.

The script in Listing 4.19 uses the FileExists method to verify the existence of the file C:\FSO\ScriptLog.txt. If the file exists, the script uses the GetFile method to bind to the file. If the file does not exist, the script echoes the message, "File does not exist."

Listing 4.19 Verifying the Existence of a File

  
1
2
3
4
5
6


Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists("C:\FSO\ScriptLog.txt") Then
 Set objFile = objFSO.GetFile("C:\FSO\ScriptLog.txt")
Else
 Wscript.Echo "File does not exist.?
End If

You cannot use wildcard characters to verify whether a particular set of files (such as .txt files) exists in a folder, nor can you use wildcards to verify whether any files at all exist in a folder. For example, the following code sample does not result in an error but always returns the value False, regardless of how many files are in the folder:



WScript.Echo objFSO.FileExists("C:\FSO\*.*")

If you need to verify the existence of a file based on some criteria other than the path, you have two options:

  • Use the GetFolder object to bind to the folder, retrieve the Files property, and then iterate through the collection of files looking for the files of interest. For example, you could enumerate all the files and file name extensions, and keep track of how many have the .doc extension.

  • Use WMI. WMI allows you to create more targeted queries, such as selecting all the files with the .doc file name extension. You can then use the Count method to determine the number of items in the collection returned to you. If Count is greater than 0, at least one file was found with the .doc extension.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft