Parsing File Paths

Microsoft® Windows® 2000 Scripting Guide

A path is a hierarchical series of names that allow you to pinpoint the exact location of a file or folder. In that respect, paths are similar to street addresses: they provide information that tells you precisely where to locate an object. A street address such as One Main Street, Redmond, WA, tells you precisely where to find a particular residence. Likewise, the path C:\FSO\Scripts\ScriptLog.txt tells you precisely where to locate a particular file. Just as only one building can be located at One Main Street, Redmond, WA, only one file can be located at C:\FSO\Scripts\ScriptLog.txt.

Complete paths such as C:\FSO\Scripts\ScriptLog.txt are very important because they provide the only way to uniquely identify a file or folder location. Because of that, there will be times when your script will need the complete path.

At other times, however, you might want only a portion of the path. For example, you might want to extract only the file name or only the file name extension. To allow you to parse paths and extract individual path components, the FileSystemObject provides the methods listed in Table 4.7.

Table 4.7 Methods for Parsing File Paths

Method

Description

GetAbsolutePathName

Returns the complete path of the file (for example, C:\FSO\Scripts\Scriptlog.txt).

GetParentFolderName

Returns the path of the folder where the file is stored (for example, C:\FSO\Scripts).

GetFileName

Returns the name of the file, minus any path information (for example, ScriptLog.txt).

GetBaseName

Returns the base name of the file, the file name minus the file name extension (for example, ScriptLog).

GetExtensionName

Returns the file name extension (for example, txt).

The script in Listing 4.30 parses the path for the file ScriptLog.txt. This script works only if ScriptLog.txt is in the same folder as the script doing the parsing. If the two files are stored in different folders, you must pass the complete path to the GetFile method (for example, C:\FSO\Scripts\ScriptLog.txt).

Listing 4.30 Parsing File Paths

  
1
2
3
4
5
6
7
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile("ScriptLog.txt")
Wscript.Echo "Absolute path: " & objFSO.GetAbsolutePathName(objFile)
Wscript.Echo ?Parent folder: ? & objFSO.GetParentFolderName(objFile)
Wscript.Echo "File name: " & objFSO.GetFileName(objFile)
Wscript.Echo "Base name: " & objFSO.GetBaseName(objFile)
Wscript.Echo "Extension name: " & objFSO.GetExtensionName(objFile)

When this script is run under CScript, output similar to the following appears in the command window:

Absolute path: C:\FSO\Scripts\ScriptLog.txt
Parent folder: C:\FSO\Scripts
File name: ScriptLog.txt
Base name: ScriptLog
Extension name: txt