【发布时间】:2016-10-01 14:53:30
【问题描述】:
我想编写一个可以访问具有文件夹路径的配置文件的 VBScript。一旦定向到该文件夹,就会有带有_DDMMYYYY 的文档。我想删除_ 和日期戳。
有人可以帮帮我吗?
Option Explicit
Dim FSO: Set FSO = CreateObject("Scripting.FileSystemObject")
'Declare the variables to be used from the property file
Dim Folder
Dim objWMIService, objProcess, colProcess, obNetwork
Dim strComputer, WshShell, strComputerName
strComputer = "."
Set obNetwork = WScript.CreateObject("Wscript.Network")
strComputerName = obNetwork.ComputerName
Set obNetwork = Nothing
SetConfigFromFile("C:\Users\Lenovo\Desktop\RenameFile\ConfigPad.txt")
MsgBox "Folder = " & Folder
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run Folder
'---------- Get Variables from ConfigPad.txt ----------
Sub SetConfigFromFile(fileName)
Dim strConfigLine
Dim fConFile
Dim EqualSignPosition
Dim strLen
Dim VariableName
Dim VariableValue
Set fConFile = fso.OpenTextFile(fileName)
While Not fConFile.AtEndOfStream
strConfigLine = fConFile.ReadLine
strConfigLine = Trim(strConfigLine)
'MsgBox(strConfigLine)
If (InStr(1,strConfigLine,"#",1) <> 1 And Len(strConfigLine) <> 0) Then
EqualSignPosition = InStr(1, strConfigLine, "=", 1)
strLen = Len(strConfigLine)
VariableName = LCase(Trim(MID(strConfigLine, 1, EqualSignPosition-1))) 'line 34
VariableValue = Trim(Mid(strConfigLine, EqualSignPosition + 1, strLen - EqualSignPosition))
Select Case VariableName
'ADD EACH OCCURRENCE OF THE CONFIGURATION FILE VARIABLES(KEYS)
Case LCase("Folder")
If VariableValue <> "" Then Folder = VariableValue
End Select
End If
Wend
fConFile.Close
End Sub
'---------- Rename the documents ----------
Dim FLD
Dim fil
Dim strOldName
Dim strNewName
Dim strFileParts
'Set the folder you want to search.
Set FLD = FSO.GetFolder("C:\Users\Lenovo\Desktop\RenameFile\RenameFile.vbs")
'Loop through each file in the folder
For Each fil in FLD.Files
'Get complete file name with path
strOldName = fil.Path
'Check the file has an underscore in the name
If InStr(strOldName, "_") > 0 Then
'Split the file on the underscore so we can get everything before it
strFileParts = Split(strOldName, "_")
'Build the new file name with everything before the
'first under score plus the extension
strNewName = strFileParts(0) & ".txt"
'Use the MoveFile method to rename the file
FSO.MoveFile strOldName, strNewName
End If
Next
'Cleanup the objects
Set FLD = Nothing
Set FSO = Nothing
我的配置文件只有这个:
Folder = "C:\Users\Lenovo\Desktop\RenameFile\Test - Copy"
【问题讨论】:
-
什么不能按预期工作?你期望代码做什么,它实际上做什么?你有错误吗?他们说什么?
-
第 60 行,找不到路径。
-
C:\Users\Lenovo\Desktop\RenameFile\RenameFile.vbs很可能是一个文件,而不是文件夹。您是否期望GetFolder返回该文件的父文件夹?这不是方法的工作原理。请改用FSO.GetFile("...").ParentFolder。 -
然后您需要使用变量
Folder调用GetFolder,其中您的其他过程存储了该路径:Set FLD = FSO.GetFolder(Folder)。 -
检查变量的值。检查该文件夹是否确实存在并且是一个文件夹。
WScript.Echo Folder & ": " & FSO.FolderExists(Folder)
标签: vbscript rename configuration-files