Microsoft

Get IT Done: Create a file renaming script with Windows Script Host

Quickly rename files with this script


In my Daily Drill Down “Getting Started with Windows Script Host,” I introduced you to the Windows Script Host and asserted that it and its accompanying scripting engines, VBScript and JScript, are packed with features and capabilities that allow you to automate just about any Windows task. These tasks include launching applications, performing file management, automating networking, and even changing the registry.

To illustrate how Windows Script Host works to automate Windows tasks, I’ll show you in this Daily Drill Down how to create a script that overcomes one of Windows' biggest file management shortcomings—the inability to rename multiple files at the same time from within My Computer and Windows Explorer. I’ll go through the script and explain in layman’s terms how it functions—so you don’t have to be a programmer to create or understand the script.

As you know, if you want to rename multiple files, you either have to rename them one by one in Windows Explorer, or you have to shell out to DOS and use the Rename command, which will allow you to use wildcard characters to rename multiple files in a single pass. Renaming files one by one is not only inefficient, it’s frustrating—especially if there are a lot of files to rename. On the other hand, many folks are unfamiliar with the often-cryptic DOS commands, and using wildcards doesn’t fit every situation. So now what do you do? This is where the Rename Files script comes in.

Prerequisites
The Rename Files script has two requirements your system must meet in order to run it. First, it requires the Windows Script 5.5 package. You can download this package from the Microsoft Windows Script Technologies site. Just follow the links to the Windows Script Host Downloads section. The Windows Script package includes Windows Script Host 2.0, VBScript 5.5, and JScript 5.5. Also, keep in mind that there are two versions of the package: one for Windows 2000 and one for Windows 95/98/NT.

Second, the script requires files provided by the Active Desktop and the newer versions of the Windows operating system. This means that if you’re using Windows 98 or Windows 2000, you’re all set. If you’re running Windows 95 or Windows NT 4.0, however, you must install Internet Explorer 4.x and the Active Desktop feature, which add the needed files to your system.

Keep in mind that the Active Desktop feature is not included in Internet Explorer 5.x. This means that if you bypassed Internet Explorer 4.x and the Active Desktop feature and went straight to Internet Explorer 5.x, you won’t be able to run this script. For more detailed information on how to remedy this situation, see the Microsoft Knowledge Base article “How to Install the Windows Desktop Update with Internet Explorer 5.x.”

If after reading this Knowledge Base article you decide to install Internet Explorer 4.x and the Active Desktop feature, you’ll be happy to know that you can still download it from Microsoft’s Web site. After you download the Ie4setup.exe program and run it, just follow the on-screen instructions to select the installation option you wish to use (Browser Only, Standard, Full) and then choose to install the Windows Desktop Update.

Choosing a scripting language
As I mentioned, the Windows Script Host natively supports both the VBScript and JScript scripting engines. Since I consider VBScript, with its close relation to Visual Basic, to be a more mainstream scripting language, I chose to develop Rename Files in VBScript. Furthermore, I’ve found that VBScript’s command structure and syntax are more robust and much easier to understand and work with when developing a script—especially when you’re first getting started. It’s important to keep in mind, however, that with a good understanding of the JScript language and syntax, you could just as easily create the Rename Files script in JScript.

An example
Before I actually show you how to create and use the Rename Files script, let’s take a moment to consider an example of renaming multiple files. Doing so will highlight the problems with the current methods and help you gain an appreciation for the simplicity with which the Rename Files script does its job. In addition, the example will give us a point of reference when I later describe how the Rename Files script works.

Let’s suppose that your company uses a standard file-naming convention for all its documents and that the filenames are made up of a short basename that indicates a department, along with the year, the month, a project number, and a file number. For example, the accounting department might use the filenames Acct010251.xls, Acct010252.xls, Acct010253.xls, etc. for its Excel documents. In this example file-naming scheme, Acct indicates the department, 01 indicates the year 2001, 02 indicates the month of February, and 5x designates the project and file number.

Now, let’s suppose that the project that these documents pertain to is delayed and is being moved from the month of February to April. As such, all the files would now need to be renamed to indicate the change of the month. This would mean that you’d have to change the month section of each filename from 02 to 04.

As you can imagine, if there are many files that pertain to this project, renaming all of the files one by one in Windows Explorer would be very tedious. To do so would mean accessing the rename text box by single-clicking the file twice, using the arrow keys to move to the month section of the filename, pressing the [Delete] key to erase the 2, typing a 4 in its place, and then pressing the [Enter] key to activate the change. This cumbersome and inefficient method of renaming multiple files not only wastes time, but it is also prone to errors.

While using the DOS Rename command, along with wildcard characters, will actually allow you to rename all the files at once, the operation can be complicated and fraught with pitfalls of its own. First, you have to access an MS-DOS prompt (also called a command prompt in Windows 2000 and NT) and then use the change directory (CD) command to navigate to the folder containing the files to be renamed. This step alone can be tricky—especially if the path to the folder is made up of long folder names or if the files are located on a network drive. If you make one little typo while entering the path, you have to start all over. Then, once you get to the folder, you have to type the Rename command along with the old filename, the wildcard characters, and the new filename. Again, if you make a typo, you have to start over.

Creating the Rename Files script
Creating the Rename Files script is simple. To begin, launch Notepad and type the Rename Files script shown in Listing A. Be sure that you type all the commands exactly as shown (but don’t type the line numbers; they are for reference only). If you don’t, the script won’t work correctly. When you’ve finished, save the file as RenameFiles.vbs.

If typing in lines of code isn’t your cup of tea, don’t worry; the RenameFiles.vbs script is available for download. To download the script, just click here.

Listing A: RenameFiles.vbsDim WshShell, FileManagement, BrowseDialogBox, SelectedFolder, OldString, NewString, FullPath, TheFolder, FileList
Dim File, ThisFile, TheString, AlreadyRenamed, TempName, FlagName, Success, FindFlag, NewName, Dummy
Set WshShell = WScript.CreateObject("WScript.Shell")
Set FileManagement = WScript.CreateObject ("Scripting.FileSystemObject")
Set BrowseDialogBox = WScript.CreateObject("Shell.Application")
Set SelectedFolder = BrowseDialogBox.BrowseForFolder(0, "Select the folder containing the files you want to rename.", &H0001)
If InStr(1, TypeName(SelectedFolder), "Folder") = 0 Then
Wscript.Quit
Else
OldString = InputBox("Enter the characters in the filename that you want to replace","Rename Files")
If OldString = "" Then Wscript.Quit
NewString = InputBox("Enter the characters that you want to replace them with","Rename Files")
‘If NewString = "" Then Wscript.Quit
End If
FullPath = SelectedFolder.ParentFolder.ParseName(SelectedFolder.Title).Path
Set TheFolder = FileManagement.GetFolder(FullPath)
Set FileList = TheFolder.Files
Success = 0
For Each File in FileList
ThisFile = File.Name
TheString = InStr(ThisFile, OldString)
AlreadyRenamed = InStr(ThisFile, "%")
If (TheString <> 0) AND (AlreadyRenamed = 0) Then
Success = 1
TempName = Replace(ThisFile, OldString, NewString)
FlagName = "%" + TempName
File.Name = FlagName
End If
Next
For Each File in FileList
ThisFile = File.Name
FindFlag = InStr(ThisFile, "%")
If FindFlag <> 0 Then
NewName = Replace(ThisFile, "%", "")
File.Name = NewName
End If
Next
If Success = 1 Then
Dummy = WshShell.Popup ("Rename Files operation complete!",5,"Rename Files",64)
Else
Dummy = WshShell.Popup ("Rename Files operation failed! Please repeat the operation.",0,"Rename Files",16)
End If
Wscript.Quit

Script overview
Before I investigate the commands in the script, let’s take a moment to provide a general overview of the script. As you’ll see, the Rename Files script prompts you to tell it where the files are that you want to rename, which characters in the filename you want to replace, and which characters you want to replace them with. It then performs a search and replace operation to actually rename the files and finally alerts you to the success of the operation.

It’s important to point out that the Rename Files script is case-sensitive. This means that if you wanted to change the Acct section in our example filenames, you’d have to be sure to use an uppercase A when prompted to indicate which characters in the filename you want to replace. If you don’t use the correct case, the Rename Files operation fails, and the script displays an error message. Likewise, if the characters don’t exist at all in the filename, the script displays an error message.

Studying the Rename Files script
Let’s take a step-by-step look at the VBScript commands in the Rename Files script. As I describe the script, I’ll use the technical term object to describe the programming. An object is a component of an operating system that provides you with a collection of subroutines (methods) and variables (properties) that you can use to work with that object from within a script. With that in mind, let's take a closer look.

Defining the variables
The first two lines in the script use the Dim statement to define the variables that the script uses.

Defining the variables at the beginning of the script is necessary in order to allocate space in memory, thus providing the script with a place to store information as it does its job.

In creating the variable names, I strayed from the traditional cryptic variable names that are typically used in VBScript. Instead, I’ve used names that more closely represent the information that the script stores in the variables. For instance, the SelectedFolder variable stores the name of the folder that contains the files you want to rename, while the FullPath variable stores the path to that folder.

Activating the Windows Script Host object model
Line 3 is special in that it is used to activate all of the features of the Windows Script Host object model. To do so, it basically links the WshShell object and the WScript object together.

As you may remember from “Getting started with Windows Script Host,” the WScript object plays a central role in the Windows Script Host object model in that it’s automatically activated when you run a script, and it provides you with the ability to create and retrieve objects, display messages, and terminate a script. When the WshShell object is activated, it provides you with direct access to the Windows Shell. Basically, the third line makes it possible for all the following commands in the script to function.

Assigning object references
Lines 4 and 5 use the Set command to assign object references to variables. Once that occurs, you can use the variables to access the methods that the objects make available.

As such, line 4 uses a Set command to assign the FileSystemObject object reference to the FileManagement variable. As I mentioned in “Getting started with Windows Script Host,” the FileSystemObject is actually provided by VBScript and is one of the most useful objects in the scripting system, as it provides you with the ability to access and manipulate files and folders.

Next, line 5 uses a Set command to assign the Application object reference to our BrowseDialogBox variable. The Application object reference refers to the methods that the Active Desktop feature makes available.

Accessing the browse dialog box
Once the script activates the Application object reference, it can access a standard Browse For Folder dialog box. To do so, the script’s next line (line 6) uses the BrowseDialogBox variable to access the BrowseForFolder method, which will then display a Browse For Folder dialog box that you can use to locate and select the folder containing the files you want to rename. Once you select a folder and click OK, the BrowseForFolder method will return the name of that folder and assign it to the SelectedFolder variable.

Prompting for input and evaluating the results
Lines 7-14 make up an If…Then…Else statement that performs several important functions in the script. Namely, this section prompts for input and evaluates the results.

Line 7 of the statement tests to see whether you’ve actually selected a folder in the Browse For Folder dialog box and clicked OK or if you clicked the Cancel button. If you clicked the Cancel button, the script calls the Windows Script Host’s built-in Quit method to terminate the script.

If you selected a folder and clicked OK, however, the line that follows the Else portion of the statement (line 10) displays an input dialog box that prompts you for the characters in the filename that you want to change and then stores those characters in the variable OldString. Line 11 tests to see whether you indeed typed any characters in the input dialog box or clicked the Cancel button. If you clicked the Cancel button, the Quit method terminates the script.

Up next in line 12, the script displays another input dialog box and prompts you for the new characters that you want to use to replace the old characters in the filename. The script then stores those characters in the variable NewString.

Notice that line 13 begins with a single quote. This single quote acts as a remark character, which essentially removes the line from the script. This line tests to see if you type any characters in the input dialog box and terminates the script if you click the Cancel button. However, removing this line from the script allows you to leave the second input dialog box blank so that you can delete characters from a filename.

Here’s how it works: If you type the filename characters that you want to replace in the first input dialog box, click OK, and then leave the second input dialog box blank and click OK, the search and replace operation will replace those characters with nothing. In other words, it deletes the characters from the filename.

But there’s a catch: If you remove this line, you can’t terminate the script by clicking the Cancel button in the second input dialog box. If you do click the Cancel button, the script will automatically assume that you want to delete the characters from the filename and proceed to do so.

While this could be considered a drawback, it actually allows the script to be more versatile and, as such, is an acceptable liability. By the time you get to the second input dialog box, you’ve already bypassed two opportunities to cancel the operation. Chances are you’re committed to the operation. If you need to, you can still effectively cancel the operation by typing the same characters that you typed in the first input dialog box in the second one.

If you prefer the ability to cancel the operation from the second input dialog box rather than deleting characters from a filename, all you have to do is remove the single quote from the beginning of line 13.

Locating the folder and the files
After the End If command completes the If…Then…Else statement, line 15 assigns the full path to the folder you selected in the browse dialog box to the FullPath variable.

Once that occurs, I use the FileManagement object variable along with the GetFolder method to basically combine the path and the name of the selected folder and assign it to a variable called TheFolder. I then use this object variable, along with the Files method, to retrieve the list of files in that folder and assign it to the FileList variable.

Creating a flag
At this point, I need to create a flag that the script will later use to determine whether or not a rename operation occurred and will then display an appropriate message that indicates the outcome of the operation. Let’s take a closer look at how this flag works.

Line 18 assigns the Success variable a value of 0, which indicates that a rename operation has not yet occurred. If a rename operation occurs, the Success variable will be assigned a value of 1. If a rename operation doesn’t occur, the Success variable will remain set to 0. Towards the end of the script, I’ll then test this value to determine whether to display a success or failure dialog box. More on this in a moment.

Renaming the file
Lines 19-29 implement a For Each…Next statement to basically go through each file in the folder and perform the search and replace operation that will actually rename the files. As the script renames each file, it saves the file back to the folder with its new name, and the operating system updates the filenames in the folder. Unfortunately, in some cases this instant updating of the filenames can cause a problem. Sometimes, depending on how your Windows OS updates filenames, the script sees newly renamed files as files it hasn’t yet renamed, and it will process them again. If that happens, the files can be renamed multiple times.

To avoid this problem, I configured the script to flag each file as it is renamed. The script then tests for the flag before processing a file. If the file is flagged, it’s already been renamed, and it isn’t processed. With this in mind, let’s take a look at the commands that make up the For Each…Next statement.

The first line in the statement (line 20) will assign a filename from the FileList variable to the File object variable. The next line then uses the File object variable to access the Name method and assigns the actual filename to the ThisFile variable. I then pass the ThisFile variable, along with the OldString variable, to the VBScript InStr function, which will basically search through the filename looking for the characters to replace.

In line 22, I perform a check to see if the file has already been renamed. To do so, I again use the VBScript InStr function but this time pass it the ThisFile variable, along with the flag character—the percent symbol (%).

If the InStr function finds the characters, it will return their position in the filename as a numeric value, and the script will then assign that value to the TheString and AlreadyRenamed variables, respectively.

Then, in line 23, I use a compound If…Then statement to test the values in the TheString and AlreadyRenamed variables.

If the value in the TheString variable is not 0 and the value in the AlreadyRenamed variable is 0, then the characters in the OldString variable were found in the filename, but the flag character (%) wasn’t. This means that the file should be renamed.

At this point, line 24 sets the Success flag to 1. The script now passes the ThisFile variable, along with the OldString and NewString variables, to the VBScript Replace function, which will actually replace the characters in the OldString variable with those in the NewString variable. The script will then return the resulting string and reassign it to the TempName variable.

In line 26, I append the flag character (%) to the beginning of the new filename and assign it to the FlagName variable.

The next line will then assign the new string to the actual filename using the Name method, thus renaming the file. The End If command then exits the If…Then statement, and the Next command starts the process over again with the next file in the folder.

Now, if the value stored in the TheString variable is 0, that means that the characters weren’t found in the filename. If the value stored in the AlreadyRenamed variable is a number other than 0, that means that the flag character (%) was found in the filename. If either of these situations occurs, execution of the script drops down to the End If command. Again, the Next command starts the process over again with the next file in the folder.

Removing the flag
After all the files in the folder have been processed, lines 30-37 implement a For Each…Next statement that checks each file in the folder again, performing a search and replace operation to remove the flag character from every file that was renamed. Since this For Each…Next statement performs an almost identical operation to the one above, I’ll cover this section briefly.

Once a filename is assigned to the ThisFile variable, I use the InStr function to search for the flag character. If the flag character is found, the Replace function replaces it with nothing, which deletes the flag character. The resulting string is assigned to the NewName variable, which is then used to assign the string to the actual filename using the Name method, thus renaming the file. The End If command then exits the If…Then statement and the Next command starts the process over again with the next file in the folder.
In this script, I chose to use the percent symbol (%) for the flag character. This symbol is a valid character for filenames but is rarely used. If you are one of the few people who uses the percent symbol, choose a different character for the flag—otherwise the script won’t work. To modify the script, all you need to do is replace every occurrence of the percent symbol with the character you want to use as a flag. In the following list, I’ve provided the special characters that are legal in Windows filenames.
Legal special characters
Character/Description
  • ^  Accent circumflex (caret)
  • & Ampersand
  • '  Apostrophe (single quotation mark)
  • @ At sign
  • {  Brace left
  • }  Brace right
  • [  Bracket opening
  • ]  Bracket closing
  • ,  Comma
  • $  Dollar sign
  • =  Equal sign
  • !  Exclamation point
  • -  Hyphen
  • #  Number sign
  • (  Parenthesis opening
  • )  Parenthesis closing
  • % Percent
  • .  Period
  • +  Plus
  • ~  Tilde
  • _  Underscore

Displaying the operation result
Once all the files in the folder have been processed, the script will display a message that indicates the success or failure of the rename operation. To do so, it uses an If…Then…Else statement.

If any of the files in the folder were renamed, the Success variable will have a value of 1, and the script will use the Windows Script Host Popup method to display an appropriately configured dialog box and a success message. Because the Popup method is actually designed to return a result, I must assign that result to the Dummy variable even though I’ll never use it.

If none of the files in the folder was renamed, the Success variable will still have a value of 0. This means that the search string was not found in any of the filenames and could indicate a misspelling, the wrong case, or a similar error. In any case, the script will use the Windows Script Host Popup method to display an appropriately configured dialog box and a failure message. Finally, the Windows Script Host Quit method terminates the script.

Using the Rename script
Now that you have a good idea of how the Rename script works, let’s take a look at it in action. To do so, let’s return to the example I set up earlier where an accounting project is being moved from February to April, and all of the corresponding files need to be renamed. To perform this operation, I need to replace the 02 portion of the filename with 04 for every file that belongs to the project.

To begin, locate the RenameFiles.vbs script file and double-click on it. When you do, you’ll see the Browse For Folder dialog box, shown in Figure A. As you can see, this dialog box provides you with the ability to browse the network, as well as local drives, to locate the folder containing the files you want to rename.

Figure A
The Browse For Folder dialog box allows you to locate and select the folder containing the files you want to rename.


Once you select the folder and click OK, the Rename Files script prompts you to provide the characters in the filename that you want to change, in this case 02, as shown in Figure B.

Figure B
The script prompts you to enter the characters that you want to replace in the filename.


When you click OK, you’ll be prompted to provide the new characters that you want to replace the old ones with in the filename, in this case 04, as shown in Figure C.

Figure C
The script prompts you to enter the characters that you want to use as replacements.


When you click OK, the Rename Files script will go to work renaming the files. Upon completion, the script will display the success dialog box shown in Figure D. This dialog box will remain on the screen for five seconds and then automatically close.

Figure D
This dialog box indicates that the Rename Files operation was a success.


If you don’t use the correct case or if the characters don’t exist in the filename, the Rename Files script displays an error message dialog box, as shown in Figure E. In order to make sure that you know the operation failed, this dialog box will remain on the screen until you click OK.

Figure E
This dialog box indicates that the Rename Files operation failed.


As you can see, the Rename Files script is far superior to the file renaming methods that Windows and DOS provide. Best of all is that the entire procedure is done with features that Windows natively provides.

Acknowledgments
I’d like to thank Gunter Born for his diligence in uncovering and documenting Internet Explorer 4.x’s BrowseForFolder method in his book Microsoft Windows Script Host 2.0 Developer’s Guide. You can find more information about this book and Mr. Born on his Windows Script Host Bazaar Web site.

Conclusion
The Windows Script Host is a powerful alternative to using batch files to automate certain tasks in Windows. In this Daily Drill Down, I’ve shown you how to use Windows Script Host and VBScript to create a tool that will allow you to quickly and easily rename multiple files in one smooth operation.
The authors and editors have taken care in preparation of the content contained herein but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for any damages. Always have a verified backup before making any changes.

About

Greg Shultz is a freelance Technical Writer. Previously, he has worked as Documentation Specialist in the software industry, a Technical Support Specialist in educational industry, and a Technical Journalist in the computer publishing industry.

Editor's Picks