VBscript将日期添加到zip文件的名称

时间:2012-06-27 18:32:50

标签: date vbscript zip

我目前有一个删除旧日志文件的脚本,然后获取比指定时间段更新的文件,并将它们压缩成一个名为localhost.zip的zip。

我想要做的只是将文件压缩后的日期添加到zip的名称上。

所以我喜欢localhost_Date.zip。

我知道我需要在“%computername%”之后添加一些内容,但我只是不确定处理它的语法。

提前感谢您的帮助。此外,如果您看到我的脚本可以进行任何改进,请告诉我。这只是一个初学者的工作,调整在线发现的其他脚本以满足我的需求。

Option Explicit

Dim oFSO, oFolder, sDirectoryPath 
Dim oFileCollection, oFile, sDir 
Dim iDaysOld 

' Specify Directory Path From Where You want to clear the old files 

sDirectoryPath = "C:\Testscripts\testfolder\"

' Specify Number of Days Old File to Delete

iDaysOld = 7

Set oFSO = CreateObject("Scripting.FileSystemObject") 
Set oFolder = oFSO.GetFolder(sDirectoryPath) 
Set oFileCollection = oFolder.Files 

For each oFile in oFileCollection

    'Specify the Extension of file that you want to delete 
    'and the number with Number of character in the file extension 



    If LCase(Right(Cstr(oFile.Name), 3)) = "log" Then

        If oFile.DateLastModified < (Date() - iDaysOld) Then 
        oFile.Delete(True) 
        End If 

    End If   
Next 



Set oFSO = Nothing 
Set oFolder = Nothing 
Set oFileCollection = Nothing 
Set oFile = Nothing 



WScript.Echo "Press to start zipping log files."

Dim objFile, objPath, objFolder, Command, PathLogs, RetVal
Dim objFSO: Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objShell: Set objShell = CreateObject("WScript.Shell")

PathLogs = "C:\Testscripts\testfolder\" 'This path just has some test logs

' Loop through the logs and zip and move each file (if required, you could just move files with an '.log' extension)


Set objPath = objFSO.GetFolder(PathLogs)
For Each objFile In objPath.Files




    If (LCase(objfso.GetExtensionName(objFile)) = "log") Then

        ' zip files

        Command = """C:\Program Files\7-zip\7z.exe"" a " & PathLogs & "%computername%" & ".zip " & PathLogs & objFile.Name 

        RetVal = objShell.Run(Command,0,true)

    End If

Next

WScript.Echo "Zip Successful."

WScript.Echo "Now Moving Zipped Files into Archived Folder"

'move files

Set objFSO = CreateObject("Scripting.FilesystemObject")
objFSO.MoveFile "C:\Testscripts\testfolder\*.zip" , "C:\Testscripts\testfolder\Archived"

WScript.Echo "Move Successful."

1 个答案:

答案 0 :(得分:0)

我跳过了血淋淋的细节,对不起。这是一个两行VBScript代码,用于将当前日期格式化为yyyy-mm-dd(请记住,文件名中不允许/):

Dim d : d = Date()
Dim dateStr : dateStr = Year(d) & "-" & Right("00" & Month(d), 2) & "-" & Right("00" & Day(d), 2)

' Usage
Command = """C:\Program Files\7-zip\7z.exe"" a " & PathLogs & "%computername%" & "-" & dateStr & ".zip " & PathLogs & objFile.Name

除此之外,这一行:

If LCase(Right(Cstr(oFile.Name), 3)) = "log" Then

可以使用FSO.GetExtensionName编写:

If LCase(oFSO.GetExtensionName(oFile.Name)) = "log" Then