VBS scripting question - manipulating dates - vbscript

I have the following code (manipulated some code from a helpful soul out in cyberspace).
What it is meant to do is to zip all .csv files in a directory and name the zip file with the current timestamp.
My problem - I have setup a scheduled task to execute the below code everyday. As you can see, I am going back a day each time the code is executed. Meaning, zipping the file today with yesterday's "day". When it runs on the 1st of every month, I obviously run into a problem. It will grab yesterday's day (which is fine) but the current month. How can I manipulate the code so that it checks if yesterday was the last day of the month and put the correct timestamp for the filename?
Any assistance is greatly appreciated.
strFilepath = "c:\files"
strDestination = "c:\files\completed\" '"#
strExtension = "csv"
strYear = Year(Now)
strMonth = Right("0" & Month(Now), 2)
strDay = Right("0" & Day(Now -1), 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

Just check Day(now) value. It it = 1, then Month = Month -1.

Related

How do I delete the oldest file in a backup folder if there is more than 15 files in the folder after I made the new backup using vbscript?

How do I delete the oldest file in a backup folder if there is more than 15 files in the folder after I made the new backup using vbscript?
I found that my Backups take up plenty of space on my hdd
Is it possible to do it by counting the number of files in a folder? My backups are named "ST-06.02.18 07h20.zip" . I can always change the name if it wil make it easier...xd
Dim objFSO, objFolder, strDirectory, dNow, yy, mt, dd, hh, nn, objShell, dOpen
Set objFSO = CreateObject("Scripting.FileSystemObject")
strDirectory = "c:\test\"
If objFSO.FolderExists(strDirectory) Then
Set objFolder = objFSO.GetFolder(strDirectory)
WScript.Echo strDirectory & " already created "
Else
Set objFolder = objFSO.CreateFolder(strDirectory)
WScript.Echo "Just created " & strDirectory
End If
dNow = Now
yy = Right(Year(dNow), 2)
mt = Right("00" &Month(dNow), 2)
dd = Right("00" &Day(dNow), 2)
hh = Right("00" &Hour(dNow), 2)
nn = Right("00" &Minute(dNow), 2)
ss = Right("00" &Second(dNow), 2)
Compress "C:\Program Files\ST\Db" ,strDirectory & "ST-" &dd & "." &mt & "." &yy & " " &hh & "h" &nn &".zip"
Sub Compress(Input, ZipFile)
Dim Shell : Set Shell = CreateObject("Shell.Application")
Dim FSO : set FSO = CreateObject("Scripting.fileSystemObject")
FSO.CreateTextFile(ZipFile, true).WriteLine "PK" & Chr(5) & Chr(6) & String(18, 0)
Set ZipFile = Shell.NameSpace(ZipFile)
ZipFile.CopyHere Input
Do Until ZipFile.items.Count = 1
'important, makes the script not fall out and dispose of objects before they are done
'items.count is the amount of root items you anticipate to be in the zip file
wscript.sleep 200
Loop
Set Shell = Nothing
Set FSO = Nothing
Set ZipFile = Nothing
End Sub
Set objShell = CreateObject("Wscript.Shell")
dOpen = "explorer.exe /e," & strDirectory
objShell.Run dOpen
Set fso = CreateObject("Scripting.FileSystemObject")
Set F = fso.GetFolder("C:\Users\David Candy\Desktop\New Folder\Stories\Test")
If F.size > 2^30 Then
Set rs = CreateObject("ADODB.Recordset")
With rs
.Fields.Append "Date", 7
.Fields.Append "Txt", 201, 5000
.Open
For Each Thing in f.files
.AddNew
.Fields("Date").value = thing.datelastmodified
.Fields("Txt").value = thing.path
.UpDate
Next
.Sort = "Date Desc"
Do While not .EOF
fso.deletefile .Fields("Txt").Value
msgbox f.size
If f.size < 2^30 then Exit Do
.MoveNext
Loop
End With
End If
This sample code runs when the folder is greater than 2 gig and deletes the oldest files until under 2 gig.
It uses a disconnected recordset created in memory to sort files by last modified.

Limiting zip file size

I have a script in VBScript that gets the content of a folder and gets it into a zip. It is mainly based on what I found in another post, as I am no VBS expert. This is the function:
Sub ArchiveFolder (zipFile, sFolder)
With CreateObject("Scripting.FileSystemObject")
zipFile = .GetAbsolutePathName(zipFile)
sFolder = .GetAbsolutePathName(sFolder)
With .CreateTextFile(zipFile, True)
.Write Chr(80) & Chr(75) & Chr(5) & Chr(6) & String(18, chr(0))
End With
End With
With CreateObject("Shell.Application")
.NameSpace(zipFile).CopyHere .NameSpace(sFolder).Items
Do Until .NameSpace(zipFile).Items.Count = _
.NameSpace(sFolder).Items.Count
WScript.Sleep 1000
Loop
End With
End Sub
I need to divide the resulting file in size limited files (80MB). Is there a way to do this?
As I understand it, the Chr(80) & Chr(75) & Chr(5) & Chr(6) & String(18, chr(0)) part is indicating to create a zip file, but I am not able to find an explanation of what this means and how to parametrize the action.
The simplest approach to limiting the size of a zip file is to continue adding files until the maximum size is exceeded, then remove the last item added.
Sub ArchiveFolder (zipFile, sFolder)
With CreateObject("Scripting.FileSystemObject")
zipFile = .GetAbsolutePathName(zipFile)
sFolder = .GetAbsolutePathName(sFolder)
With .CreateTextFile(zipFile, True)
.Write Chr(80) & Chr(75) & Chr(5) & Chr(6) & String(18, chr(0))
End With
Set oZip = .GetFile(zipFile)
End With
With CreateObject("Shell.Application")
cnt = 0
For Each currentItem In .NameSpace(sFolder).Items
cnt = cnt + 1
.NameSpace(zipFile).CopyHere currentItem
Do Until .NameSpace(zipFile).Items.Count = cnt
WScript.Sleep 1000
Loop
If oZip.Size > 83886080 Then
Set lastItem = .NameSpace(zipFile).ParseName(f.Name)
.NameSpace("C:\temp").MoveHere lastItem
Exit For
End If
Next
End With
End Sub
Of course there are more intelligent strategies than this to optimize space usage, but exploring them would be far too broad for an answer here.
I have finally solved it by using 7zip's portable version. There I can create the zip file with the parameters I need:
Set oShell = CreateObject("WScript.Shell")
strCmd = "7-Zip\7z.exe a -v80m " & zipFile & " " & sFolder
oShell.Run(strCmd)
Set oShell = Nothing

zipping files within VB script

I have a script that works perfectly for me to move files, create new folders then delete out old ones, however i am unable to add in a zipping function. I can do this separately but would like it in my script as i only want to run the one scheduled task.
Can anyone help?
Dim theDate, ArchiveDate
Dim CurPath
Dim BackupPath
Dim objFSO, objFolder, objFile
Dim ArchivePath
'theDate = InputBox("Date to archive (ddmmyy)")
theDate = DateAdd("d",-1, date())
dateArray = Split(theDate,"/")
theDate = dateArray(0) & dateArray(1) & Right(dateArray(2),2)
CurPath = CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(".")
BackupPath = CurPath & "\" & thedate
ArchiveDate = CDate(left(theDate,2) & "/" & mid(theDate,3,2) & "/" & right(theDate,2))
ArchivePath = "E:\Log_Folder_1"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(CurPath)
'msgbox CurPath
'msgbox BackupPath
'msgbox ArchiveDate
For Each objFile In objFolder.Files
ModifiedDate = Split(objFile.DateLastModified," ")
If (CDate(ModifiedDate(0)) = ArchiveDate AND objFSO.GetExtensionName(objFile) <> "vbs") Then
'msgbox "yes " & objFile.DateLastModified
If objFSO.FolderExists(BackupPath) = false Then
objFSO.CreateFolder(BackupPath)
End If
objFile.Move BackupPath & "\" & objFile.Name
Else
'msgbox "no " & objFile.DateLastModified
End If
Next
dim filesys
set filesys=CreateObject("Scripting.FileSystemObject")
If filesys.FolderExists(BackupPath) Then
filesys.CopyFolder "E:\Log_Folder_1" & "\" & thedate, "\\Backup_Server\Logs\Log_Folder_1"
End If
If objFSO.FolderExists(CurPath & "\" & theDate) Then
Set delFolder = objFSO.GetFolder(CurPath & "\" & theDate)
delFolder.Delete
End If
Dim keepDays
keepDays = -20
Do Until keepDays=-10
theDate = replace(DateAdd("d",keepDays, date()),"/","")
theDate = left(theDate,4) & right(theDate,2)
If objFSO.FolderExists ("\\Backup_Server\Logs\Log_Folder_1" & "\" & theDate) Then
Set delFolder = objFSO.GetFolder("\\Backup_Server\Logs\Log_Folder_1" & "\" & theDate)
delFolder.Delete
End If
keepDays=keepDays+1
Loop

Looking for a VBScript to move files older than 3 years to a new folder while keeping the folder structure

I am looking to move files from my file server to a tape drive to save space. I need a script that will allow me to move all the files that were accessed 3 years ago or later while still keeping their folder structure.
E.g. d:\share\it\test.txt -> d:\archive\share\it\test.txt, assuming the test.txt file hasn't been accessed in 3 years
I will then run a tape backup over this folder.
I have some scripts that I have been using. The most effective one I have used is this one, but tt doesn't recreate the file structure in the test folder :
Dim objFSO, ofolder, objStream, strSafeDate, strSafeTime, strDateTime, strLogFileName
Set objShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("scripting.filesystemobject")
Set objNet = CreateObject("WScript.NetWork")
Set FSO = CreateObject("Scripting.FileSystemObject")
strSafeDate = DatePart("yyyy",Date) & Right("0" & DatePart("m",Date), 2) & Right("0" & DatePart("d",Date), 2)
strSafeTime = Right("0" & Hour(Now), 2) & Right("0" & Minute(Now), 2) & Right("0" & Second(Now), 2)
Set strDateTime equal to a string representation of the current date and time, for use as part of a valid Windows filename
strDateTime = strSafeDate & "-" & strSafeTime
'Assemble the path and filename
strLogFileName ="Move File " & strDateTime & ".txt"
set outfile = fso.createtextfile(strLogFileName,true)
SPath = "I:\Tech Docs"
Sdest = "I:\Test\"
ShowSubfolders FSO.GetFolder(spath)
Sub ShowSubFolders(Folder)
For Each Subfolder in Folder.SubFolders
CheckFolder(subfolder)
ShowSubFolders Subfolder
Next
End Sub
'CheckFolder(objFSO.getFolder(SPath))
Sub CheckFolder(objCurrentFolder)
Dim strTempL, strTempR, strSearchL, strSearchR, objNewFolder, objFile
Const OverwriteExisting = TRUE
currDate = Date
dtmDate = DateAdd("d",-0,Now)
strTargetDate = ConvDate(dtmDate)
For Each objFile In objCurrentFolder.Files
FileName = objFile
'WScript.Echo FileName
'strDate = ConvDate(objFile.DateCreated)
strDate = ConvDate(objFile.DateLastAccessed)
If strDate < strTargetDate Then
objFSO.MoveFile FileName, Sdest
outfile.writeline Filename
End If
Next
End Sub
Function ConvDate (sDate) 'Converts MM/DD/YYYY HH:MM:SS to string YYYYMMDD
strModifyDay = day(sDate)
If len(strModifyDay) < 2 Then
strModifyDay = "0" & strModifyDay
End If
strModifyMonth = Month(sDate)
If len(strModifyMonth) < 2 Then
strModifyMonth = "0" & strModifyMonth
End If
strModifyYear = Year(sDate)
ConvDate = strModifyYear & strModifyMonth & strModifyDay
End Function
`
Dim objFSO, ofolder, objStream, strSafeDate, strSafeTime, strDateTime, strLogFileName
Set objShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("scripting.filesystemobject")
Set objNet = CreateObject("WScript.NetWork")
Set FSO = CreateObject("Scripting.FileSystemObject")
strSafeDate = DatePart("yyyy",Date) & Right("0" & DatePart("m",Date), 2) & Right("0" & DatePart("d",Date), 2)
strSafeTime = Right("0" & Hour(Now), 2) & Right("0" & Minute(Now), 2) & Right("0" & Second(Now), 2)
Set strDateTime equal to a string representation of the current date and time, for use as part of a valid Windows filename
strDateTime = strSafeDate & "-" & strSafeTime
'Assemble the path and filename
strLogFileName ="Move File " & strDateTime & ".txt"
set outfile = fso.createtextfile(strLogFileName,true)
SPath = "I:\Tech Docs\"
Sdest = "I:\Test\"
ShowSubfolders FSO.GetFolder(spath)
Sub ShowSubFolders(Folder)
CheckFolder Folder
For Each Subfolder in Folder.SubFolders
ShowSubFolders Subfolder
Next
End Sub
'CheckFolder(objFSO.getFolder(SPath))
Sub CheckFolder(objCurrentFolder)
Dim strTempL, strTempR, strSearchL, strSearchR, objNewFolder, objFile
Const OverwriteExisting = TRUE
currDate = Date
dtmDate = DateAdd("d",-0,Now)
strTargetDate = ConvDate(dtmDate)
For Each objFile In objCurrentFolder.Files
'Since we want to preserve the path, we've got to reconstruct it
sAbsPath = objFile.Path
'Swap source and destination in the path, and strip the file name
'from the path.
sNewPath = Replace(Replace(sAbsPath,sPath,Sdest),"\" & objFile.Name,"")
'Here we reconstruct the path if it doesn't exist in the
'destination with our new Sub "MakeDir"
MakeDir sNewPath
FileName = objFile
'WScript.Echo FileName
'strDate = ConvDate(objFile.DateCreated)
strDate = ConvDate(objFile.DateLastAccessed)
If strDate =< strTargetDate Then
'Finally we copy the file to the sNewPath
objFSO.MoveFile FileName, sNewPath & "\"
outfile.writeline Filename
End If
Next
End Sub
Sub MakeDir(strPath)
On Error Resume Next
strParentPath = objFSO.GetParentFolderName(strPath)
If Not objFSO.FolderExists(strParentPath) Then MakeDir strParentPath
If Not objFSO.FolderExists(strPath) Then objFSO.CreateFolder strPath
On Error Goto 0
End Sub
Function ConvDate (sDate) 'Converts MM/DD/YYYY HH:MM:SS to string YYYYMMDD
strModifyDay = day(sDate)
If len(strModifyDay) < 2 Then
strModifyDay = "0" & strModifyDay
End If
strModifyMonth = Month(sDate)
If len(strModifyMonth) < 2 Then
strModifyMonth = "0" & strModifyMonth
End If
strModifyYear = Year(sDate)
ConvDate = strModifyYear & strModifyMonth & strModifyDay
End Function

Script to download file by name according to date on a Windows?

I need to daily run a script that will download a file from a fixed location (http://www.meteoman.it/ilmeteo/audio/) and save it on my computer.
The format of filename is yyyy-mm-dd.mp3 and everyday a new file in added.
The script must recognize the date and save the appropriate file whit the date of today in the folder "today" and the file whit the date of tomorrow in the folder "tomorrow".
thank you !!!
the script if for automate the forecast on my web-radio
the file of forecast are freeware
sorry for my English!
cheers from Italy
The calls to Right are to pad the month and day with a leading zero if needed (adds a zero to any month/day and then extract only the last 2 digits).
dt = Date
yearStr = Year(dt)
monthStr = Right("0" & Month(dt), 2)
dayStr = Right("0" & Day(dt), 2)
fileName = yearStr & "-" & monthStr & "-" & dayStr & ".mp3"
To get tomorrow's date, just change the first line to:
dt = DateAdd("d", 1, Date)
here the script ! tnx all!
dt = Date
yearStr = Year(dt)
monthStr = Right("0" & Month(dt), 2)
dayStr = Right("0" & Day(dt), 2)
fileName = yearStr & "-" & monthStr & "-" & dayStr & ".mp3"
' Set your settings
strFileURL = "http://www.meteoman.it/ilmeteo/audio/" & filename
strHDLocation = "c:\today\today.mp3"
' Fetch the file
Set Ws = WScript.CreateObject("WScript.Shell")
Set objXMLHTTP = CreateObject("MSXML2.XMLHTTP")
objXMLHTTP.open "GET", strFileURL, false
objXMLHTTP.send()
If objXMLHTTP.Status = 200 Then
Set objADOStream = CreateObject("ADODB.Stream")
objADOStream.Open
objADOStream.Type = 1 'adTypeBinary
objADOStream.Write objXMLHTTP.ResponseBody
objADOStream.Position = 0 'Set the stream position to the start
Set objFSO = Createobject("Scripting.FileSystemObject")
If objFSO.Fileexists(strHDLocation) Then objFSO.DeleteFile strHDLocation
Set objFSO = Nothing
objADOStream.SaveToFile strHDLocation
objADOStream.Close
Set objADOStream = Nothing
End If
' Set objXMLHTTP = Nothing
' Ws.Run strHDLocation
' Set WS = Nothing

Resources