我正在尝试编写一个vbscript来递归重命名文件夹中的任何文件。 我的最终计划是将文件夹复制到zip文件,但如果文件除
之外还有任何字符,则会失败例如(a-z)或(0-9)或“_”,“”。
例如,如果文件名中的文件中包含英文以外的字符,则不允许我将文件复制到zip文件中。我查看了各种网站,也可以批量回答。
我对正则表达式很陌生,昨天开始学习它。
我得到的错误是“文件已存在”。
我的剧本:
Const ForReading = 1
Const ForWriting = 2
Const ForAppend = 8
Const OverwriteExisting = TRUE
scriptdir = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName)
Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = scriptdir & "\Fragments"
Set objFolder = objFSO.GetFolder(objStartFolder)
Set colFiles = objFolder.Files
Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.Global = True
objRegEx.Pattern = "[^A-Za-z_0-9-\n\r]"
For Each objFile in colFiles
If regEx.test(objFile.Name) = true Then
FirstlevelNewFileName = objRegEx.Replace(objFile.Name, "_")
objFSO.MoveFile objFile, FirstlevelNewFileName
End If
Next
ShowSubfolders objFSO.GetFolder(objStartFolder)
Sub ShowSubFolders(Folder)
For Each Subfolder in Folder.SubFolders
Set objFolder = objFSO.GetFolder(Subfolder.Path)
Set colFiles = objFolder.Files
For Each objFile in colFiles
NewFileName = objRegEx.Replace(objFile.Name, "_")
objFSO.MoveFile objFile.Path, NewFileName
Next
ShowSubFolders Subfolder
Next
End Sub
感谢您的时间!
答案 0 :(得分:1)
我认为您的代码在Movefile
语句中遇到问题(当您尝试重命名文件时)。您只提供文件名作为Destination参数。你应该在那里提供完整的路径。我已做出如下所示的更改。
注意:我没有改变任何逻辑。
Const ForReading = 1
Const ForWriting = 2
Const ForAppend = 8
Const OverwriteExisting = TRUE
scriptdir = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName)
Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = scriptdir & "\Fragments"
Set objFolder = objFSO.GetFolder(objStartFolder)
Set colFiles = objFolder.Files
Set objRegEx = new Regexp
objRegEx.Global = True
objRegEx.Pattern = "[^\w.]" 'looks for non-word characters and also not .(for the extension)
For Each objFile in colFiles
If objRegEx.test(objFile.Name) = true Then 'Changed this. You had only used the variable RegEx here instead of objRegEx
FirstlevelNewFileName = objRegEx.Replace(objFile.Name, "_")
objFile.Move objStartFolder&"\"&FirstlevelNewFileName 'Provided the full file path here. Used the File Object itself
EndIf
Next
ShowSubfolders objFSO.GetFolder(objStartFolder)
Sub ShowSubFolders(Folder)
For Each Subfolder in Folder.SubFolders
Set objFolder = objFSO.GetFolder(Subfolder.Path)
Set colFiles = objFolder.Files
For Each objFile in colFiles
NewFileName = objRegEx.Replace(objFile.Name, "_")
objFile.Move Subfolder.Path&"\"&NewFileName 'passed the full path here again
Next
ShowSubFolders Subfolder
Next
End Sub