Click here to Skip to main content
11,582,850 members (68,748 online)
Click here to Skip to main content

How to Rename Multiple Files with VBS

, 24 Jun 2008 CPOL 115.8K 1.1K 20
Rate this:
Please Sign up or sign in to vote.
VBScript code which can rename multiple files in a folder by replacing certain patterns and extensions.

og-bit rename files

Introduction

I usually have the need to rename several files located on a particular folder. The files can have a particular string pattern which I would like to remove and/or an extension I want to change. I usually come across these scenarios when I script out the objects from a database to text files. When I extract tables and stored procedures, I usually create many files which could have a particular pattern and extension that needs to be changed. For example, I like to use the extension TAB instead of SQL for table scripts.

I wrote this script to allow me to facilitate the batch renaming of files.

Background

This scripts uses the Scripting.FileSystemObject COM object. This object is used to access a computer's file system. This allows you to create and alter existing files.

Using the code

This script iterates through all the files found in a particular folder. It searches for string and extension patterns in each file. If the pattern is found, it is replaced by the new string and extension that was provided.

The command line syntax to run the script is as follows:

cscript rename.vbs [folder path] [string to replace] 
        [new string] [old extension] [new extension]
[folder path] folder location
[string to replace] pattern to find
[new string] new string to replace pattern with
[old extension] extension to find (optional)
[new extension] new extension (optional)

The usage is:

cscript rename.vbs . test ozkar txt tab

If one only needs to replace the extension for all the files, enter the extension pattern to replace as the [string to replace] parameter. The script is written to allow you to replace two patterns at once, only when the first pattern is found.

The code is divided into three main areas. The entry point Main handles the parameter validation. A reference to the FileSystemObject is assigned to the fso variable. The arguments are referenced by the objArgs variable which holds an array of values. The first three parameters are required. The last two parameters are optional. Once the parameters are validated, fso.GetFolder is called to get a handle for that folder. A warning is issued to allow the user to confirm the task. The ProcessFolder function is then called to rename the files.

Option Explicit

Dim StdIn:  Set StdIn = WScript.StdIn
Dim StdOut: Set StdOut = WScript
Dim fso:    Set fso = CreateObject("Scripting.FileSystemObject")

Dim FilesRenamed:   FilesRenamed = 0
Dim FilesSkipped:   FilesSkipped = 0

Main

set fso = nothing

Sub Main
      
   'get the parameter list   
   dim objArgs: Set objArgs = WScript.Arguments

   if objArgs.Count > 2 then
      
    dim path: path = objArgs(0)  'path
    dim olds: olds = objArgs(1)  'string to replace
    dim news: news = objArgs(2)  'new string
    
    dim ext1: ext1 = ""
    dim ext2: ext2 = ""
    if objArgs.Count > 3 then ext1 = objArgs(3)  'old extension
    if objArgs.Count > 4 then ext2 = objArgs(4)  'new extension            

    dim CurrentFolder: Set CurrentFolder = fso.GetFolder(path)
    StdOut.Echo "Warning: All files within the directory """ & _
                CurrentFolder.Path & """ will be renamed."
    If Not Confirm("Continue?") Then Exit Sub
    
    ProcessSubFolders CurrentFolder , olds, news, ext1,ext2
    
    StdOut.Echo "Files renamed :" & FilesRenamed
    StdOut.Echo "Files Skipped :" & FilesSkipped 
    
   else
       StdOut.Echo "Usage: rename.vbs [folder path] [string to replace]" & _ 
                   " [new string] [old extension] [new extension] "
   end if
   
End Sub

The Confirm function echoes a message and waits for the standard input to return. The user must enter Y to continue.

Function Confirm (ByVal promptText)   
      StdOut.Echo promptText & " (y/n) "
      Dim s: s =  StdIn.ReadLine()      
      Select Case LCase(Trim(s))         
         Case "y"         
            Confirm = True
            exit function 
         Case else            
             Confirm = False
             exit function            
      End Select      
         
End Function

The ProcessSubFolder function iterates through all the sub-folders in the current directory, and it recursively calls the same function for each sub-folder found. This allows it to search down the tree of folders. For each folder found, it calls the ProcessFolder function.

Sub ProcessSubFolders (ByVal crfolder, ByVal oldTag, ByVal newTag, ByVal extOld, ByVal extNew)
  Dim Folders: Set Folders = crfolder.SubFolders
  Dim Folder 'process the current folder 
  ProcessFolder crfolder , oldTag, newTag, extOld,extNew
  For Each Folder in FoldersNext 
      ProcessSubFolders Folder , oldTag, newTag, extOld,extNew
  End
Sub 

The ProcessFolder function does all the hard work. It iterates through all the files in the folder. If it finds the patterns in the file name, it checks to see if the extension pattern was also provided. It then replaces all the string patterns and calls File.Move.

Sub ProcessFolder (ByVal folder, ByVal oldTag, ByVal newTag, ByVal extOld, ByVal extNew)
   Dim Files: Set Files = folder.Files
   
   Dim File
   For Each File In Files
   
      If inStr(1,File.Name,oldTag) > 0 Then
      
         if (extOld <> "" and extNew <> "") then
            StdOut.Echo Replace(Replace(File.Path,oldTag,newTag),extOld,extNew)
            File.Move Replace(Replace(File.Path,oldTag,newTag),extOld,extNew)
         else
            StdOut.Echo Replace(File.Path,oldTag,newTag)
            File.Move Replace(File.Path,oldTag,newTag)
         end if
                  
         FilesRenamed = FilesRenamed + 1
      Else
         FilesSkipped = FilesSkipped + 1
       End If
   Next
End Sub

Points of interest

I hope this simple script can be useful to some of you as it has been to me.

History

  • 0g10112006 - Initial version.
  • 0g10232007 - Added process subfolders.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

ozkar garcia
Architect OG-BITechnologies
United States United States

You may also be interested in...

Comments and Discussions

 
QuestionNeed Help Pin
Member 117551459-Jun-15 22:18
memberMember 117551459-Jun-15 22:18 
QuestionWorks nicely Pin
Member 98886266-Mar-13 4:20
memberMember 98886266-Mar-13 4:20 
QuestionError Message on Launch Pin
AyoAdegbokun4-Mar-13 21:01
memberAyoAdegbokun4-Mar-13 21:01 
AnswerRe: Error Message on Launch Pin
ozkar garcia5-Mar-13 7:55
memberozkar garcia5-Mar-13 7:55 
GeneralRe: Error Message on Launch Pin
AyoAdegbokun6-Mar-13 1:34
memberAyoAdegbokun6-Mar-13 1:34 
GeneralRe: Error Message on Launch Pin
ozkar garcia6-Mar-13 3:33
memberozkar garcia6-Mar-13 3:33 
GeneralRe: Error Message on Launch Pin
AyoAdegbokun7-Mar-13 21:11
memberAyoAdegbokun7-Mar-13 21:11 
GeneralRe: Error Message on Launch Pin
ozkar garcia8-Mar-13 2:45
memberozkar garcia8-Mar-13 2:45 
Generalplzz help Pin
Amar Venkat Jammula8-Feb-11 21:03
memberAmar Venkat Jammula8-Feb-11 21:03 
GeneralRe: plzz help Pin
ozkar garcia9-Feb-11 3:38
memberozkar garcia9-Feb-11 3:38 
QuestionRe: plzz help [modified] Pin
Amar Venkat Jammula9-Feb-11 18:46
memberAmar Venkat Jammula9-Feb-11 18:46 
AnswerRe: plzz help Pin
ozkar garcia10-Feb-11 3:55
memberozkar garcia10-Feb-11 3:55 
QuestionRe: plzz help Pin
Amar Venkat Jammula10-Feb-11 18:21
memberAmar Venkat Jammula10-Feb-11 18:21 
AnswerRe: plzz help Pin
ozkar garcia11-Feb-11 6:31
memberozkar garcia11-Feb-11 6:31 
GeneralRe: plzz help Pin
Amar Venkat Jammula11-Feb-11 19:26
memberAmar Venkat Jammula11-Feb-11 19:26 
GeneralRe: plzz help Pin
ozkar garcia14-Feb-11 3:29
memberozkar garcia14-Feb-11 3:29 
Generali am not able to execute pls help Pin
Amar Venkat Jammula8-Feb-11 20:59
memberAmar Venkat Jammula8-Feb-11 20:59 
GeneralBuen Ejemplo Pin
smercado9-Oct-09 6:56
membersmercado9-Oct-09 6:56 
Questionmsgbox Pin
qsdf98714-Nov-08 0:59
memberqsdf98714-Nov-08 0:59 
GeneralSome fix on the sub fodler process. Pin
klchiang22-Jun-08 1:18
memberklchiang22-Jun-08 1:18 
Believe that is some typo error, tested fail, so here is the fixed coding.

Sub ProcessSubFolders (ByVal crfolder, ByVal oldTag, ByVal newTag, ByVal extOld, ByVal extNew)
Dim Folders: Set Folders = crfolder.SubFolders 'process the current folder
Dim Folder
ProcessFolder crfolder , oldTag, newTag, extOld,extNew
For Each Folder in Folders
ProcessSubFolders Folder , oldTag, newTag, extOld,extNew
next
end Sub

Wink | ;) good tools !!
GeneralRe: Some fix on the sub fodler process. Pin
ozkar garcia24-Jun-08 9:20
memberozkar garcia24-Jun-08 9:20 
GeneralExcellent vbs. thanks Pin
nw18-Mar-08 17:10
membernw18-Mar-08 17:10 
QuestionRecurse Pin
joky504910-Oct-07 7:23
memberjoky504910-Oct-07 7:23 
AnswerRe: Recurse Pin
ozkar23-Oct-07 8:37
memberozkar23-Oct-07 8:37 
GeneralGreat Article Pin
edpatterson19-Sep-07 6:40
memberedpatterson19-Sep-07 6:40 
GeneralRe: Great Article Pin
ozkar25-Sep-07 8:57
memberozkar25-Sep-07 8:57 
QuestionRe: Great Article Pin
Amar Venkat Jammula13-Feb-11 19:40
memberAmar Venkat Jammula13-Feb-11 19:40 
GeneralGood Tool! Pin
Shola Salako20-Apr-07 4:54
memberShola Salako20-Apr-07 4:54 
GeneralRe: Good Tool! Pin
ozkar25-Sep-07 8:58
memberozkar25-Sep-07 8:58 
GeneralRe: Good Tool! Pin
Amar Venkat Jammula13-Feb-11 19:39
memberAmar Venkat Jammula13-Feb-11 19:39 
QuestionIsn't it already possible directly from the prompt? Pin
impavide1-Nov-06 3:04
memberimpavide1-Nov-06 3:04 
AnswerRe: Isn't it already possible directly from the prompt? Pin
ozkar1-Nov-06 3:41
memberozkar1-Nov-06 3:41 
AnswerRe: Isn't it already possible directly from the prompt? Pin
edpatterson25-Sep-07 11:26
memberedpatterson25-Sep-07 11:26 
GeneralCScript not WScript [modified] Pin
gxdata31-Oct-06 16:15
membergxdata31-Oct-06 16:15 
GeneralRe: CScript not WScript Pin
ozkar1-Nov-06 3:29
memberozkar1-Nov-06 3:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150603.1 | Last Updated 24 Jun 2008
Article Copyright 2006 by ozkar garcia
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid