Search and Zip (revised and improved)
This is a little vbs script I wrote the other day. It's purpose is to find all log files in a given directory, create a zip archive (using 7-Zip command line interface) of each individual file (created before today, so I don't zip anything currently in use) and delete the original file.
I hope somebody else finds it useful... Although I know that someone can probably out best me with a Perl one-liner..
Here goes!
'Function: Compress and delete log files
'Description: Finds all files with the extension ".log"
'from inside the folder(s) passed as arguments, create a ".zip"
'archive with the same name and delete the original file
'Example: cscript compress.vbs d:\logs "d:\big app logs"
strComputer = "."
str7z = "C:\7-Zip\7z.exe"
i=0
If WScript.Arguments.Count = 0 then
WScript.Echo "Directory path missing. Usage: cscript zippit.vbs dir1 ""dir 2"" (etc)"
Else
'For each folder passed as an argument
For Each strArgument in WScript.Arguments
strDir = WScript.Arguments.Item(i)
Set oShell = WScript.CreateObject("WScript.Shell")
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
'fiel collection inside strDir folder
Set colFiles = objWMIService.ExecQuery _
("ASSOCIATORS OF {Win32_Directory.Name='"& strDir &"'} Where " _
& "ResultClass = CIM_DataFile")
'Process monitor; will report upon closed \ finished processes
Set colMonitoredProcesses = objWMIService. _
ExecNotificationQuery("select * from __instancedeletionevent " _
& "within 1 where TargetInstance isa 'Win32_Process'")
If colFiles.Count >0 Then
'for each file
For Each objFile In colFiles
'only logs mater.any other file is skiped
If WMIDateStringToDate(objFile.CreationDate) > now() And objFile.Extension = "txt" Then
'compression routine
oShell.Run ""& str7z &" a -tzip """& strDir &"""\"& objFile.FileName &".zip "_
& " """& strDir &"""\"& objFile.FileName &".txt"
WScript.Echo "Created the file "& strDir &"\"& objFile.FileName &".zip "
'log deletion routine
z = 0
'wainting Loop (sleep until zip is done)
Do While z = 0
Set objLatestProcess = colMonitoredProcesses.NextEvent
If objLatestProcess.TargetInstance.Name = "7z.exe" Then
'7z process ended; i can leave the waiting loop and delete the original file
objFile.Delete
WScript.Echo "Deleted the file "& strDir &"\"& objFile.FileName &"."& objFile.Extension &" "
z = 1
Exit Do
End If
Loop
End If
Next
End if
i = i+1
Next
End If
'change date format returned by wmi_script
Function WMIDateStringToDate(dtmDate)
WMIDateStringToDate = CDate(Mid(dtmDate, 5, 2) & "/" & _
Mid(dtmDate, 7, 2) & "/" & Left(dtmDate, 4) _
& " " & Mid (dtmDate, 9, 2) & ":" & _
Mid(dtmDate, 11, 2) & ":" & Mid(dtmDate, _
13, 2))
End Function
WScript.Quit
'as with everything else on this blog.... Creative Commons apply to this code.
No comments:
Post a Comment