http://www.chrispearson.org/pages/programming/vbscript/renamescript.asp
17h08
Thursday, 28. August 2008

COLLATING FILES

Often you'll collect folders full of files from downloads which have a diversity of naming conventions. Or several folders of related files which, for one reason or another, have replicated file names - Image1.gif in one folder but Image2.gif and Image1.jpg in other folders.

This VBScript takes each file in a named folder and renames it, with its original extension, placing it in a second, destination folder.

Set fso = CreateObject("Scripting.FileSystemObject")
FolderPath = "D:\Temp"
Set DataFolder = fso.GetFolder(FolderPath)
Set Files = DataFolder.Files
intFilesCount = Files.Count
'
msgbox "There are " & intFilesCount & " files in " & FolderPath
'
FileID = 1
For Each File in Files
   ThisFile = FolderPath & "\" & File.Name
   Extension = right(ThisFile, 4)
   If left(Extension, 1) <> "." Then
      Extension = ".???"
   End If
   FileTo = right("00000" & FileID, 5) & Extension
   FileID = FileID + 1
   set f2 = fso.GetFile(ThisFile)
   f2.copy("D:\CopyFile\" & FileTo)
   set f2 = Nothing
Next
'
set fso = Nothing

This script can be saved as a .vbs file and executed from Windows Explorer, from the command line or called from another program or script.

Note that the input folder, D:\Temp, and the destination folder, D:\CopyFile, are both hardcoded into this example.

The script uses the Windows file system object to first count the files in the input folder; the message box reports the number of files. Clicking on OK allows the body of the script to execute.

Each file in the input folder is read. Starting at index number 1, the files are written out to the destination folder. In this example the index is contained in a five-character field left-padded with zeros (Done rather explicitly here)

The output file path is generated in the script and a brief instance of a second file system object is created to copy the file from the input folder to the destination folder.

 

 

Note that the files can be moved with renaming using the fso.Move in place of fso.Copy
The Windows file system object is immensely powerful and can be used not only in interactive scripts like this one but also in active server pages. There is extensive documentation on the web including, not surprisingley, at microsoft.com: See the scripting homepage at http://msdn.microsoft.com/scripting/ for starters.

xxx,xxx

copyright ©2000 - 2008 Chris Pearson