Last active
December 21, 2015 18:39
-
-
Save cabrel/6348490 to your computer and use it in GitHub Desktop.
prefix directory name to each file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
' | |
' Usage: `cscript prefix.vbs C:\path\to\folder\root` | |
' | |
Dim folderList, fileList, rootPath | |
rootPath = WScript.Arguments.Item(0) | |
folderList = Split(ShowFolderList(rootPath), ",") | |
For i = 0 to UBound(folderList) | |
RenameFiles folderList(i) | |
Next | |
' | |
' ShowFolderList("C:\Path") | |
' | |
Function ShowFolderList(path) | |
Dim fso, folder, subFlds, fld, s | |
Set fso = CreateObject("Scripting.FileSystemObject") | |
Set folder = fso.GetFolder(path) | |
Set subFlds = folder.SubFolders | |
s = "" | |
For Each fld in subFlds | |
s = s & path & "\" & fld.name | |
s = s & "," | |
Next | |
' remove the trailing comma | |
s = Left(s, Len(s) - 1) | |
ShowFolderList = s | |
End Function | |
' | |
' ShowFileList("C:\Path") | |
' | |
Sub RenameFiles(path) | |
Dim fso, folder, files, subFolders, oldFilePath, newFilePath, alreadyModified | |
Set fso = CreateObject("Scripting.FileSystemObject") | |
Set folder = fso.GetFolder(path) | |
Set subFolders = folder.SubFolders | |
For Each subFolder in subFolders | |
Set files = subFolder.Files | |
For Each file in files | |
oldFilePath = path & "\" & subFolder.name & "\" & file.name | |
newFilePath = path & "\" & subFolder.name & "\" & folder.name & file.name | |
alreadyModified = Left(file.name, Len(folder.name)) | |
' To avoid prepending the folder name AGAIN, check to see if | |
' the prefix is already there | |
' | |
' This could break with legitimate folder names having the folder | |
' prefix | |
If alreadyModified <> folder.name Then | |
fso.MoveFile oldFilePath, newFilePath | |
Wscript.Echo "Moved '" & oldFilePath & "' to '" & newFilePath & "'" | |
Else | |
Wscript.Echo "It appears '" & oldFilePath & "' has already been renamed" | |
End If | |
Next | |
Next | |
End Sub |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The path in the usage comment 'C:\path\to\folder\root' is expecting a structure like:
C:\path\to\folder\root:
Then the script will take the directory name and prepend it to each file name. For example:
The 3 files will be renamed and become: