Monday, February 16, 2009

QTP Script 28 - How to rename all subfolders within a given folder?

Type the below code in a notepad, save it with .vbs extension and run it from command prompt.
In case nothing is entered for main_folder or search_string or replace_string, the script will quit.

main_folder = inputbox ("Enter the main folder whose subfolders need to be renamed" & vbcrlf & "e.g. C:\Folder")
if main_folder="" then quit_function

search_string = inputbox ("Enter the string to be searched")
If search_string = "" then quit_function

replace_string = inputbox ("Enter the string to be replaced")
If replace_string = "" then quit_function

Set object_FSO= CreateObject ("Scripting.FileSystemObject")

rename_function main_folder

Sub rename_function (byval Folder)
GetFolder method is used to get the Folder object for the path that you specify. You can then use the new variable containing the folder object to access its various methods and properties.
Set object_folder = object_FSO.GetFolder (Folder)
SubFolder property returns a Folders collection consisting of all the subfolders in a given folder.
Set sub_folders = object_folder.Subfolders
For each subfolder in sub_folders
new_foldername = (Replace (, search_string, replace_string))
If new_foldername <> subfolder.Name Then
subfolder.Name = new_foldername
End If
rename_function subfolder.path
End Sub

Sub quit_function
wscript.echo "Script quit_function"
End sub