VBS script to rename files using the pathname

2019-09-12 10:14发布

问题:

i am new to VBS scripting and I have done few stuff with Excel VBA before. Now I have a script which renames single files with the pathname of the files (truncated to 4 letter each))see below. It is some script which I modified a bit to fit my purpose. However, I would like to automatize the file rename process and rename all files in a folder and its subfolders in the same way the scipt works for single files. Can anybody help me with this question?

Set Shell = WScript.CreateObject("WScript.Shell")
Set Parameter = WScript.Arguments
For i = 0 To Parameter.Count - 1
    Set fso = CreateObject("Scripting.FileSystemObject")
    findFolder = fso.GetParentFolderName(Parameter(i))
    PathName = fso.GetAbsolutePathName(Parameter(i))
    FileExt = fso.GetExtensionName(Parameter(i))
    Search = ":"
    findFolder2= Right(PathName, Len(PathName) - InStrRev(PathName, Search))
    arr = Split(findFolder2, "\")
    For j=0 To UBound(arr)-1
    arr(j) = ucase(Left(arr(j), 4))
    Next
    joined = Join(arr, "%")   
    prefix = right(joined, len(joined)-1)    
    fso.MoveFile Parameter(i), findFolder + "\" + prefix 
next

Hoping that I can get some useful ideas.

Herbie

回答1:

Walking a tree requires recursion, a function calling itself for each level.

On Error Resume Next
Set fso = CreateObject("Scripting.FileSystemObject")
Dirname = InputBox("Enter Dir name")
ProcessFolder DirName

Sub ProcessFolder(FolderPath)
    On Error Resume Next
    Set fldr = fso.GetFolder(FolderPath)

    Set Fls = fldr.files
    For Each thing in Fls
         msgbox Thing.Name & " " & Thing.DateLastModified 
    Next

    Set fldrs = fldr.subfolders
    For Each thing in fldrs
        ProcessFolder thing.path
    Next

End Sub

From Help on how to run another file.

Set Shell = WScript.CreateObject("WScript.Shell")
shell.Run(strCommand, [intWindowStyle], [bWaitOnReturn]) 

So outside the loop,

Set Shell = WScript.CreateObject("WScript.Shell")

And in the loop

shell.Run("wscript Yourscript.vbs thing.name, 1, True) 

Also the VBS help file has recently been taken down at MS web site. It is available on my skydrive at https://1drv.ms/f/s!AvqkaKIXzvDieQFjUcKneSZhDjw It's called script56.chm.