Recurse through directories and rename/append file names based on parent dirs
I have a directory with a bunch of subdirectories.
MAIN_DIR\
Each sub-dir is a "project name", e.g.
MAIN_DIR\BOBEVANS324
MAIN_DIR\BILLJOHNSON3
Each "project" folder contains a bunch of sub-dirs in it. Let's say I was looking for ".abc" files that all have names that make no sense without looking at the folder structure. For exam开发者_高级运维ple,
MAIN_DIR\BOBEVANS234\SUBDIR\3904902490.abc
As you can see "3904902490.abc" doesn't make any sense outside the context of the directory tree. I'd want to rename it by appending the directory names to the filename after copying the file.
So, it would look through ALL subfolders of MAIN_DIR and try to find ".abc" files. When it finds one, it copies it over to a dest directory and renames it something like "BOBEVANS234_SUBDIR_3904902490.abc".
You want to look at the FileSystemObject, especially the Folder Object and it's SubFolders and Name (to create the new names) properties and the File Object and it's Move Method (remember, if you move a file to a different name in the same directory, it will have the same effect as a rename).
To find the files to rename, you'll have to look for them by hand unfortunately, though it is reasonably easy as can be seen in this MS KB article (it's written for VB6 but that's very similar to VBScript): HOW TO: Recursively Search Directories by Using FileSystemObject
Here is my recursion function that i use for my scripts, You may use it as well
NOTE You must use Recurse, NOT RecurseX recursex is used by Recurse Function.
NOTE: If there is a LOT of subdirectories then Recursion may take a while.
The Recurse function will return an ARRAY containing all the folders and EVERY subfolder.
for example:
Dim I, SubDirectories
SubDirectories=Recurse ("MAIN_DIR")
For I=0 To UBound (SubDirectories)
WScript.Echo SubDirectories (I)
Next
'##########################################
'# #
'# Function #
'# #
'# Recurse Function #
'# by Ronnie Matthews #
'##########################################
'# #
'# This will return an array of all #
'# Folders and subfolders (every levels) #
'# in a directory provided. #
'# #
'##########################################
Function Recurse (dir)
Dim FSO
Set FSO = CreateObject("Scripting.Filesystemobject")
If Not FSO.FolderExists (dir) Then
Recurse=Array (Empty)
Exit Function
End If
Dim RecArr, RecArrID
RecArr=Array (dir)
RecArrID=1
Recurse=RecurseX (dir,RecArr,RecArrID)
RecArr=Empty
RecArrID=Empty
End Function
'DO NOT CALL THIS FUNCTION DIRECTLY. ONLY RECURSE
Function RecurseX (Dir,RecArr,RecArrID)
Dim F,FSO
Set FSO = CreateObject("Scripting.Filesystemobject")
For Each F In FSO.GetFolder (dir).SubFolders
ReDim Preserve RecArr (RecArrID)
RecArr (RecArrID)=F.Path
RecArrID=RecArrID+1
If F.SubFolders.Count>=1 Then
RecurseX=RecurseX (F.Path,RecArr,RecArrID)
End If
Next
RecurseX=RecArr
End Function
精彩评论