The
next three lines set the appropriate objects (for further documentation on
these objects, check http://msdn.microsoft.com/scripting/).
The For...Next structure that follows does the real work: this particular
example uses a special form of the loop intended to cycle through all the elements
of an object collection. In this case, the collection contains the filenames
of all the files in the specified folder. The Replace function (built into
VBScript) then does the search and replace for each individual filename.
Lastly, the FileCount variable tallies the number of files renamed, the result
of which is displayed in the final code section.
Example 9-6. File-renaming script
On Error Resume Next
FolderName = InputBox("Enter the name of the folder:")
If Not FolderExists(FolderName) Then WScript.Quit
SearchText = InputBox("Type the text to look for:")
ReplaceText = InputBox("Type the text with which to replace" _
& SearchText & ":")
If SearchText = "" or ReplaceText = "" Then WScript.Quit
Set FileObject = CreateObject("Scripting.FileSystemObject")
Set FolderObject = FileObject.GetFolder(FolderName)
Set FilesObject = FolderObject.Files
FileCount = 0
For Each Filename in FilesObject
If InStr(Filename.Name,SearchText) Then
Filename.Name = Replace(Filename.Name,SearchText,ReplaceText)
FileCount = FileCount + 1
End If
Next
If FileCount > 0 Then
MsgBox FileCount & " files were renamed."
Else
MsgBox "No filenames containing " & SearchText & " were found.
Pages:
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769