Rename all Files in a Folder
Posted by admin - Mar 31, 2008 Articles, Dani Vainstein, Files, Folders, QTips 0 0 Views : 196 Receive Updates For This Category
Article Tools
- Print this page
- Add Comment
- Send to Friend
- Last Updated on :
Jul 16, 2011
Sometimes we need to rename all the files in a given folder, either by appending the date, changing the file extension.
The following example simulates a backup operation, by renaming all files extensions in the LOG folder from .log to .bak.
The Script assumes that you already have a folder under location C:\LOG and assumes that the folder contains at least 1 xxxx.log file.
Option Explicit
Dim wmiService, fileList, fileData
Dim errResult, newName
Set wmiService = GetObject( "Winmgmts:root\cimv2" )
Set fileList = wmiService.ExecQuery("ASSOCIATORS OF {Win32_Directory.Name='C:\LOG'} Where ResultClass = CIM_DataFile")
For Each fileData In fileList
newName = fileData.Drive & fileData.Path & fileData.FileName & "." & "bak"
errResult = fileData.Rename( newName )
Next
If you’re planning on modifying this script to meet your own needs, there are two key points to keep in mind.
First, notice that we use an AssociatorsOf query in order to return a collection of all the files found in a folder (in this case, the folder C:\Logs )
Set fileList = wmiService.ExecQuery( _
"ASSOCIATORS OF {Win32_Directory.Name='C:\LOG'} Where ResultClass = CIM_DataFile")
An AssociatorsOf query does pretty much what the name implies: it enables you to associate two WMI classes.
In this case, we are associating Win32_Directory (the class that lets us manage folders) with CIM_DataFile (the class that lets us manage files).
You might think that the Win32_Directory class would have a property named Files that would list all the files found in that folder.
For some reason, though, it doesn’t. Instead, we have to use an AssociatorsOf query to achieve the same effect,
For more information about AssociatorsOf see WMI SDK at
http://msdn.microsoft.com/library/en-us/wmisdk/wmi/swbemservices_associatorsof.asp
The other thing to keep in mind is the fact that when you rename a file using WMI, you must pass the entire file path to the Rename method.
Suppose you want to rename the file C:\Logs\File1.log to C:\Logs\File1.bak. This line of code won’t do it:
errResult = objFile.Rename( "File1.bak" )
Instead, you’ll have to use this line of code:
errResult = objFile.Rename( "C:\Logs\File1.bak" )
That’s why the code preceding the Rename method looks so complicated:
we have to construct the entire path for our new file name, assign it to the variable newName, then pass newName to the Rename method
Based on “Can I Use a Script to Rename All the Files in a Folder?” from the Scripting Guys.


