我有一个用于压缩旧文件并删除它们的脚本。该脚本在所有其他目录中都能正常工作,但一个特定目录将无法工作。它会尝试压缩它,但最终只会创建一个名为的空 zip 文件Program.7z
。这让我认为脚本中的空格没有被正确转义。我在路径中使用了双引号和单引号,并检查了文件路径的连接。我还没有发现可能是什么问题。有什么想法吗?
Const fileZillaLogs = "C:\Program Files (x86)\Server\Logs"
Const zipProgram = """C:\Program Files\7-Zip\7zG.exe"""
Const zipArgs = "a -mx9"
Dim intZipAge
intZipAge = 7
Dim intDelAge
intDelAge = 90
Call DeleteLogFiles(fileZillaLogs, intZipAge, intDelAge)
Function DeleteLogFiles(strLogPath, intZipAge, intDelAge)
Const bDEBUG = True
Dim objFs
Dim objFolder
Dim objSubFolder
Dim objFile
Dim objWShell
Dim strCommand
Dim iResult
Set objWShell = CreateObject("WScript.Shell")
Set objFs = CreateObject("Scripting.FileSystemObject")
If Right(strLogPath, 1) <> "\" Then
strLogPath = strLogPath & "\"
End If
If objFs.FolderExists(strLogPath) Then
Set objFolder = objFs.GetFolder(strLogPath)
For Each objSubFolder in objFolder.subFolders
DeleteLogFiles strLogPath & objSubFolder.Name, intZipAge, intDelAge
Next
For Each objFile in objFolder.Files
If bDebug Then wscript.echo vbTab & "reviewing file = " & strLogPath & objFile.Name
If DateDiff("d",objFile.DateLastModified,Date) > intDelAge Then
If bDebug Then wscript.echo "Deleting because its old" End If
objFs.DeleteFile(strLogPath & objFile.Name)
Else If DateDiff("d",objFile.DateLastModified,Date) > intZipAge _
And (Right(objFile.Name, 4) = ".log") Then
If bDebug Then wscript.echo vbTab & "zipping file = " & objFile.Path
strCommand = zipProgram & " " & zipArgs & " " & objFile.Path & ".7z" & " " & objFile.Path
iResult = objWShell.Run(strCommand, 0, "false")
If bDebug Then wscript.echo vbTab & "zipping result = " & iResult
If bDebug Then wscript.echo vbTab & "deleting file = " & strLogPath & objFile.Name
objFs.DeleteFile(strLogPath & objFile.Name)
End If
End If
Next
Set objFs = Nothing
Set objFolder = Nothing
Set objWShell = nothing
End If
End Function
答案1
您的问题在第 41 行。您的对象文件路径其中有空格,但您将其添加到命令行参数中。这意味着空格应该用引号括起来,但您不能使用引号,因为它们用于连接字符串。然后您必须转义最终结果字符串中应该有的引号。在 VBS 中,转义字符是双引号字符。所以您的第 41 行应该是这样的:
strCommand = zipProgram & " " & zipArgs & " " & """" & objFile.Path & ".7z" & """" & " " & """" & objFile.Path & """"
注意“”“”序列,其基本计算方式如下:
- 第一个双引号:字符串的开头
- 第二个双引号:转义下一个字符
- 第三个双引号:是您想要在最终字符串中出现的字符
- 第四个双引号:字符串结尾
我测试过了,效果很好。每次使用对象文件路径功能。