Binding to a File

Microsoft® Windows® 2000 Scripting Guide

The FileSystemObject provides a number of methods, such as the CopyFile and DeleteFile methods, that allow a script to act on a file without creating an instance of the File object. Other tasks, however, require the File object. For example, to retrieve a list of file properties, a script must first bind to that file and then retrieve the properties.

The GetFile method allows you to bind to an individual file. To do this, you create an instance of the FileSystemObject and then create an instance of the File object. When using the GetFile method in a script, you must:

  • Specify the path to the file. The path can be referenced by using either a local path or a UNC path (for example, \\accounting\receivables\scriptlog.txt). However, you cannot use wildcards within the path, nor can you specify multiple files. GetFile can bind to only a single file at a time.

  • Use the Set keyword when assigning the path to a variable. The Set keyword is required because it indicates that the specified variable is an object reference.

For example, the script in Listing 4.18 binds to the file C:\FSO\ScriptLog.txt.

Listing 4.18 Binding to a File

  
1
2
Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.GetFile("C:\FSO\ScriptLog.txt")

In general, it is a good idea to pass the absolute path as the GetFile parameter; this ensures that the script will always be able to locate the file in question. However, it is possible to use relative paths. For example, the following code sample will work provided that ScriptLog.txt is in the same folder as the script attempting to bind to it:

objFSO.GetFile("ScriptLog.txt")

Likewise, the next code sample will work if ScriptLog.txt is in the parent folder of the script attempting to bind to it:

objFSO.GetFile(".\ScriptLog.txt")

Please note, however, that the FileSystemObject will not use the path environment variable to search for files. For example, you can start Calculator from the command prompt by typing calc.exe, regardless of the current drive or directory, because the operating system searches all folders in the path to locate the file. This does not happen with the GetFile method. The following code sample will fail unless the script is running in the C:\Windows\System32 folder, the same folder where calc.exe is located:

objFSO.GetFile("calc.exe")