
我有一個用於壓縮舊文件並刪除它們的腳本。該腳本在所有其他目錄中都可以正常工作,但在一個特定目錄中將無法運作。它將嘗試將其壓縮,但最終只會建立一個名為 .zip 的空 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行。obj檔案路徑其中有空格,但您將其添加到命令列參數中。這意味著空格應該封裝在引號中,但不能使用引號,因為它們用於連接字串。然後,您必須轉義最終結果字串中應包含的引號。在 VBS 中,轉義字元是雙引號字元。所以你的第 41 行應該是這樣的:
strCommand = zipProgram & " " & zipArgs & " " & """" & objFile.Path & ".7z" & """" & " " & """" & objFile.Path & """"
注意“”“”序列,它們基本上是這樣計算的:
- 第一個雙引號:字串的開頭
- 第二個雙引號:轉義下一個字符
- 第三個雙引號:是您想要在最終字串中出現的字符
- 第四個雙引號:字串結尾
我測試了一下,效果很好。每次使用時都必須逃脫obj檔案路徑功能。