Zipping a large folder fails - vbscript

I am trying to archive logs to capture an intermittent fault where my logs are regularly overwritten. I wish to archive the logs to ensure I capture the required event.
I have written what appears to be funcional code to perform this, however if the folder is very large, the zip fails. If I point it to a smaller directory, it works without issue.
There is no error generated, and I would appreciate any assistance in identifying the cause.
As I have never programmed in VBS before, I apologise in advance if this seems a simple question.
Option Explicit
dim objFSO, objFolder, FolderToZip, ziptoFile
dim ShellApp, eFile, oNewZip, strZipHeader
dim ZipName, Folder, i, Zip
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("D:\Program Files\afolder")
Wscript.Sleep 2000
Set oNewZip = objFSO.OpenTextFile("C:\Archive\logs_" & day(date) & month(Date) & Year(date)& ".zip", 8, True)
strZipHeader = "PK" & Chr(5) & Chr(6)
For i = 0 to 17
strZipHeader = strZipHeader & Chr(0)
Next
oNewZip.Write strZipHeader
oNewZip.Close
Set oNewZip = Nothing
WScript.Sleep 5000
FolderToZip = "D:\Program Files\afolder"
ZipToFile = "C:\Archive\logs_" & day(date) & month(Date) & Year(date)& ".zip"
Set ShellApp = CreateObject("Shell.Application")
Set Zip= ShellApp.NameSpace(ZipToFile)
Set Folder= ShellApp.NameSpace(FolderToZip)
Zip.CopyHere(FolderToZip)
WScript.Sleep 2000

Your code is a little more complicated than it needs to be, but it works in principle. What's causing the failures you're experiencing with large folders is the fixed 2 second delay at the end:
WScript.Sleep 2000
CopyHere runs asynchronously, meaning that it runs in the background while the script continues. However, after 2 seconds delay the script terminates (and the Shell.Application instance with it), whether CopyHere has finished or not. When you have numerous/large files the processing may well take more than 2 seconds.
That's why your script works fine for small folders, but not for large ones. The copying simply isn't finished when the script terminates after 2 seconds.
To avoid this, replace the fixed delay with a check that compares the number of processed files to the total file count:
Set fso = CreateObject("Scripting.FileSystemObject")
Set app = CreateObject("Shell.Application")
zipfile = "C:\Temp\logs_" & Day(Date) & Month(Date) & Year(Date) & ".zip"
fldr = "C:\Temp\sample"
cnt = fso.GetFolder(fldr).Files.Count
'create a new empty zip file
fso.OpenTextFile(zipfile, 2, True).Write "PK" & Chr(5) & Chr(6) _
& String(18, Chr(0))
'start copying the files from the source folder to the zip file
Set zip = app.NameSpace(zipfile)
zip.CopyHere app.NameSpace(fldr).Items '<- runs asynchronously!
'wait for CopyHere to finish
Do
WScript.Sleep 100
Loop Until zip.Items.Count = cnt

Related

Why can't I copy a file to a location using an environment variable?

I have this code that copies outlook PST files, and when used with the full location file path it runs perfectly fine. I've added a method to run %UserProfile% in the first line as this needs to be run in a domain context from GPO and doing it individually is non-feasible. This runs and closes outlook and reopens it at the appropriate time except one thing is amiss.
It is no longer copying the appropriate files. I echoed the initial %userprofile% sections and it is reading the correctly as "drive letter"\users\userprofile. I'm not sure where this is breaking or how to identify it.
'===================BEGIN MODIFY====================================
Set objShell = CreateObject("WScript.Shell")
userProfilePath = objShell.ExpandEnvironmentStrings("%UserProfile%")
'Set the amount of pst-files you want to copy. Start counting at 0!
ReDim pst(1)
'Define the location of each pst-file to backup. Increase the counter!
pst(0) = "%UserProfile%\AppData\Local\Microsoft\Outlook\PST\Outlook Data File - mike.pst"
pst(1) = "%UserProfile%\AppData\Local\Microsoft\Outlook\PST\Archive.pst"
'Define your backup location
BackupPath = "%UserProfile%\Documents\Outlook Backups\"
'Keep old backups? TRUE/FALSE
KeepHistory = FALSE
'Maximum time in milliseconds for Outlook to close on its own
delay = 30000 'It is not recommended to set this below 8000
'Start Outlook again afterwards? TRUE/FALSE
start = TRUE
'===================STOP MODIFY====================================
'Close Outlook
Call CloseOutlook(delay)
'Outlook is closed, so we can start the backup
Call BackupPST(pst, BackupPath, KeepHistory)
'Open Outlook again when desired.
If start = TRUE Then
Call OpenOutlook()
End If
Sub CloseOutlook(delay)
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
'If Outlook is running, let it quit on its own.
For Each Process in objWMIService.InstancesOf("Win32_Process")
If StrComp(Process.Name,"OUTLOOK.EXE",vbTextCompare) = 0 Then
Set objOutlook = CreateObject("Outlook.Application")
objOutlook.Quit
WScript.Sleep delay
Exit For
End If
Next
'Make sure Outlook is closed and otherwise force it.
Set colProcessList = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = 'Outlook.exe'")
For Each objProcess in colProcessList
objProcess.Terminate()
Next
Set objWMIService = Nothing
Set objOutlook = Nothing
set colProcessList = Nothing
End Sub
Sub BackupPST(pst, BackupPath, KeepHistory)
Set fso = CreateObject("Scripting.FileSystemObject")
If KeepHistory = True Then
ArchiveFolder = Year(Now) & "-" & Month(Now) & "-" & Day(Now)
BackupPath = BackupPath & ArchiveFolder & "\"
End If
For Each pstPath in pst
If fso.FileExists(pstPath) Then
fso.CopyFile pstPath, BackupPath, True
End If
Next
Set fso = Nothing
End Sub
Sub OpenOutlook()
Set objShell = CreateObject("WScript.Shell")
objShell.Run "Outlook.exe"
End Sub
When you declared userProfilePath = objShell.ExpandEnvironmentStrings("%UserProfile%"), you put the path of %UserProfile% in the variable named userProfilePath, but afterward you don't use this variable. That's a problem, because a few lines down, what you end up doing is declaring pst(#) with %userprofile% as a string, which doesn't work.
In other words, the %UserProfile% environment path/string needs to be expanded before being used as a path.
Your code would work if you used the userProfilePath variable you declared:
'Define the location of each pst-file to backup. Increase the counter!
pst(0) = userProfilePath+"\AppData\Local\Microsoft\Outlook\PST\Outlook Data File - mike.pst"
pst(1) = userProfilePath+"\AppData\Local\Microsoft\Outlook\PST\Archive.pst"
'Define your backup location
BackupPath = userProfilePath"\Documents\Outlook Backups\"
instead of
'Define the location of each pst-file to backup. Increase the counter!
pst(0) = "%UserProfile%\AppData\Local\Microsoft\Outlook\PST\Outlook Data File - mike.pst"
pst(1) = "%UserProfile%\AppData\Local\Microsoft\Outlook\PST\Archive.pst"
'Define your backup location
BackupPath = "%UserProfile%\Documents\Outlook Backups\"

Read music file length in VBScript

I was just wondering if there was a way to get the length of an mp3 file in seconds through VBScript into a variable.
(Adapted from my answer to a similar question about JScript.)
You can use the GetDetailsOf method of the Windows Shell Folder object to get the audio file length. This technique supports all audio file types whose metadata can be read and displayed by Windows Explorer natively.
However, note that the index of the Length attribute is different on different Windows versions: it's 21 on Windows XP/2003 and 27 on Windows Vista+. See this page and this my answer for details. You will need to take this into account in your script.
Example code:
Const LENGTH = 27 ' Windows Vista+
' Const LENGTH = 21 ' Windows XP
Dim oShell : Set oShell = CreateObject("Shell.Application")
Dim oFolder : Set oFolder = oShell.Namespace("C:\Music")
Dim oFile : Set oFile = oFolder.ParseName("Track.mp3")
Dim strLength : strLength = oFolder.GetDetailsOf(oFile, LENGTH)
WScript.Echo strLength
Example output:
00:05:18
Using Windows Media Player Control library is another way. Before using this make sure the path is correct.
Function MediaDuration(path)
With CreateObject("Wmplayer.OCX")
.settings.mute = True
.url = path
Do While Not .playState = 3 'wmppsPlaying
WScript.Sleep 50
Loop
MediaDuration = Round(.currentMedia.duration) 'in seconds
'MediaDuration = .currentMedia.durationString 'in hh:mm:ss format
.Close
End With
End Function
WScript.Echo MediaDuration("C:\media\song.mp3")
Set objShell = CreateObject("Shell.Application")
Set Ag=Wscript.Arguments
set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.RegWrite "HKLM\Software\Microsoft\Windows\CurrentVersion\App Paths\" & Wscript.ScriptName & "\", Chr(34) & Wscript.ScriptFullName & Chr(34)
WshShell.RegWrite "HKLM\Software\Microsoft\Windows\CurrentVersion\App Paths\" & Left(Wscript.ScriptName, Len(Wscript.ScriptName)-3) & "exe" & "\", Chr(34) & Wscript.ScriptFullName & Chr(34)
Set Fldr=objShell.NameSpace(Ag(0))
Set FldrItems=Fldr.Items
Set fso = CreateObject("Scripting.FileSystemObject")
Set DeskFldr=objShell.Namespace(16)
FName=fso.buildpath(DeskFldr.self.path, "Folder Property List.txt")
Set ts = fso.OpenTextFile(FName, 8, vbtrue)
For x = 0 to 50
t1 = t1 & Fldr.GetDetailsOf(vbnull, x) & " (Shell)" & vbtab
Next
ts.write FLDR.self.path &vbcrlf
ts.Write T1 & vbcrlf
T1=""
For Each FldrItem in FldrItems
For x = 0 to 50
t1 = t1 & Fldr.GetDetailsOf(FldrItem, x) & vbtab
Next
t1=t1 & vbcrlf
ts.Write T1
T1=""
Next
'msgbox FName & "has a tab delimited list of all properties"
If you drop a folder on the above it will generate a list of all shell properties for files in the folder. I don't have any mp3 files. It will depend on what software you have installed as to what will happen. Wma files leave duration blank. And the properties change dramatically from Windows version to version.
The first loop gets the properties that are available (by passing null for folderitem), the second the properties for each folderitem.

VBScript that Opens an ini file and a Config file in notepad

I work in a hospital environment and right now im doing PC deployments. Part of the deployment requires us to view 2 files on a network drive looking for information regarding the old systems. They use specific ports and or TTY's to view information in each department.
I am trying to create a VBS file that can open 2 files in 2 different notepad windows. The first one opens up but the pcview.cfg keeps giving me an error. Im trying to link to the same location that the HBOWEM32 is pointed to. Can anyone solve? For security reasons I have taken out the exact location of the network drive. The code below prompts for a specific folder name which is the old pc name. After entering that data it opens the HBOWEM32 files fine but says it cannot find the other part. I Have manually looked inside the folder and the pcview.cfg file DOES exist. I just want a faster way of opening these rather than brute forcing through the run prompt.
Here is the code.
CONST strDir = "<Netowrk Location)"
Dim WshShell
set objShell = CreateObject("WScript.Shell")
set objFSO = CreateObject("Scripting.FileSystemObject")
function findFolder(strDir, strFlag)
set objFolder = objFSO.GetFolder(strDir)
for each objSubFolder in objFolder.SubFolders
if (inStr(objSubFolder.Name, strFlag)) then
findFolder = objSubFolder.Path
exit function
else
findFolder = findFolder (objSubFolder.Path, strFlag)
end if
next
end function
strFlag = inputBox("Enter Computer Name:")
strWeb = findFolder(strDir, strFlag) & "\HBOWEM32.ini"
objShell.Run strWeb
Set WshShell = CreateObject ("WScript.Shell")
WshShell.Run ("notepad.exe """ + "\\<same location as above>\Pcview.cfg""")
Use Option Explicit
Don't create variables you don't use (WshShell, objShell)
Improve your variable names (strFlag seems to be a computer name, strWeb seems to be the full specification of a file)
Don't lump different info into one variable (strWeb contains the folder path to re-use and the specific file name)
Use diagnostics output (at least while developing)
In code:
Option Explicit
...
Dim strComputer : strComputer = InputBox("Enter Computer Name:")
Dim strFolder : strFolder = findFolder(strDir, strComputer)
Dim strIniFSpec : strIniFSpec = objFSO.BuildPath(strFolder, "HBOWEM32.ini")
WScript.Echo "will run '" & strIniFSpec & "'"
objShell.Run strIniFSpec
Dim WshShell : Set WshShell = CreateObject("WScript.Shell")
Dim strCfgFSpec : strCfgFSpec = objFSO.BuildPath(strFolder, "Pcview.cfg")
Dim strCmd : strCmd = "notepad.exe """ & strCfgFSpec & """"
WScript.Echo "will run '" & strCmd & "'"
WshShell.Run strCmd
(not tested, please be carefull)

Beginner VBscript: script that zips log files

I am having a problem with my script not actually producing a zip file. When I test the script with the paths set to something like this:
C:\Users\Bob\Desktop\Folder1\Folder2
with the test log files in folder 1 being deleted if older than 7 days, and being zipped and moved to folder 2, it will run perfectly fine. It will produce the zipped file with all of the log files in it and have the proper naming set.
So I know that at least the logic of the script works for that.
My problem is that I need this script to go through the security logs on a machine and delete any older than 7 days, and then zip up any that are left and be sent to a mounted shared drive. When I change the path to something like:
C:\Windows\System32\Config (where the logs are located)
it will still delete any log files older than 7 days, but it does not produce a zip file with any that are left. It just does nothing even though the script produces no errors. I've been trying to figure this out with no luck going over my code. If anyone could take a look over what I've had and let me know where I've gone astray that would be extremely helpful.
Thank you in advance, the script is found below.
'READ FIRST
'------------------------------------------------------------------------------------------
'Lines 14-53 delete any log files older than 7 days. Changing the value in "iDaysOld =" will change the time frame in which files are kept or deleted.
'If files do not need to be deleted this part of the script can be taken out and the Archive/Move ability will still be intact
'Lines 57-102 contain the ability to Zip your log files and send them to a new folder. The zipped file is named after the localhost and a date/timestamp is appended to the file name.
'------------------------------------------------------------------------------------------
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:\Windows\System32\config"
' 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(oFSO.GetExtensionName(oFile.Name)) = "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")
Dim d : d = Date()
Dim dateStr : dateStr = Year(d) & "-" & Right("00" & Month(d), 2) & "-" & Right("00" & Day(d), 2)
Dim t : t = Time()
Dim timeStr: timeStr = Hour(t) & "-" & Right("00" & Minute(t), 2) & "-" & Right("00" & Second(t), 2)
'Path where logs are located
PathLogs = "C:\Windows\System32\config"
'Loop through the logs and zip
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%" & "-" & dateStr & "-" & timeStr & ".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:\Windows\System32\config\*.zip" , "C:\Testscripts\testfolder\Archived"
WScript.Echo "Move Successful."
I'd probably try echoing out the 7zip command line, checking that it looks right and running it manually from the same location as the script runs from. It might look wrong when you see it or 7zip might give you a message to indicate what's going on.

SFTP transfer file and move file to folder

This is my first post so please excuse my ignorance. I am using a vbscript to zip all .csv type files in a particular folder. After some google searches, I have found a workable vbscript to do this and have enabled a scheduled task to automate this.
What I need to do next is to transfer the zip file via sftp and then "move" that zip file into another folder. I believe the former can be achieved using pscp.exe via command line but can someone show me how to do the latter?
Basically the zipping will be done twice a day and so it will have a timestamp similar to yyyymmdd0900.zip (for 9am schedule) and yyyymmdd1800.zip (for 6pm schedule). After the transfer, I want to move (not copy) the zip file generated into another folder.
Any pointers would be greatly appreciated. Thank you all in advance.
EDIT: Here is some code I slapped together based on some Google searches. It does what I want it to do. Please excuse the "pasting" as i couldn't figure out how to format it properly. Currently, it runs the bat file after copying but I just noticed that i need to send (using PuTTY Secure Copy) the "latest" zip file before moving it to the "completed" folder. Can someone please show me how to do this?
Zipping the file and rename the zip file
My Code :
On Error Resume Next
strFilepath = "c:\files"
strDestination = "c:\files\completed\"
strExtension = "csv"
strYear = Year(Now)
strMonth = Right("0" & Month(Now), 2)
strDay = Right("0" & Day(Now), 2)
strHour = Right ("0" & Hour(Now), 2)
strMinute = Right ("0" & Minute (Now), 2)
strZip = strFilepath & "\" & strYear & strMonth & strDay & strHour & strMinute & ".zip"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(strFilepath)
For Each objFile in objFolder.Files
strFileExt = objFSO.GetExtensionName(objFile.Path)
If LCase(strFileExt) = LCase(strExtension) Then
ZipFile objFile.Path, strZip
End If
Next
Sub ZipFile(strFileToZip, strArchive)
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Not objFSO.FileExists(strArchive) Then
Set objTxt = objFSO.CreateTextFile(strArchive)
objTxt.Write "PK" & Chr(5) & Chr(6) & String(18, Chr(0))
objTxt.Close
End If
Set objApp = CreateObject( "Shell.Application" )
intCount = objApp.NameSpace(strArchive).Items.Count + 1
objApp.NameSpace(strArchive).CopyHere strFileToZip
Do
WScript.Sleep 200
set objNameSpace = objApp.NameSpace(strArchive)
If Not objNameSpace is nothing Then
If objNameSpace.Items.Count = intCount Then
Exit Do
End If
End If
Loop
End Sub
>Move file to a different folder and then run a bat file to secury copy file to a FTP location
'Vars
Dim objFSO, objFileCopy, objFileDelete, dot, files, file
Dim strDestination, folder, subfolder, fileCount, strFilePath
'Strings
strDestination = "C:\Files\Completed\"
strFilePath = "C:\Files"
set objFSO = CreateObject("Scripting.fileSystemObject")
set folder = objFSO.getFolder(strFilePath)
For Each file In folder.files
Set objFileCopy = objFSO.GetFile(file)
If objFSO.GetExtensionName(file) = "zip" Then
objFSO.MoveFile objFileCopy.Path, strDestination
End If
Next
Dim shell
Set shell=createobject("wscript.shell")
Shell.run "C:\testsend.bat"
Set shell=nothing
This will move a file to the specified location.
Sub Move_File(Source_File, Destination_Folder)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
fso.MoveFile Source_File, Destination_Folder
Set fso = Nothing
End Sub
sftp client provides a means to change working directory on the host before performing any file transfers. It would be better to thus transfer the file directly to the target location.
NOTE: The above answer was a result of misunderstanding the question. I read it to mean the file had to be moved on the destination but the real operation was to move the file on the origin.
I found the following example code that moves a file after checking that it exists. Wildcards are allowed for the source parameter but then FileExists may not work. Requires vbscript 2.0 to work.
<%
dim filesys
set filesys=CreateObject("Scripting.FileSystemObject")
If filesys.FileExists("c:\sourcefolder\anyfile.html") Then
filesys.MoveFile "c:\sourcefolder\anyfile.html", "c:\destfolder\"
End If
%>

Resources