I would like to delete 7 days older, files. folders and empty folders - vbscript

I would like to delete 7 days older, files and empty folders. i have used below scripts from the link, but some files and folders are not getting deleted since the souce is pointing directly to drive letter. However, if we change the source folder c:\temp\lab everythings workes fine.
Const Active = True
Const sSource = "E:"
Const MaxAge = 7 'days
Const Recursive = True
Checked = 0
Deleted = 0
Set oFSO = CreateObject("Scripting.FileSystemObject")
if active then verb = "Deleting """ Else verb = "Old file: """
CheckFolder oFSO.GetFolder(sSource)
WScript.echo
if Active then verb = " file(s) deleted" Else verb = " file(s) would be deleted"
WScript.Echo Checked & " file(s) checked, " & Deleted & verb
Sub CheckFolder (oFldr)
For Each oFile In oFldr.Files
Checked = Checked + 1
If DateDiff("D", oFile.DateLastModified, Now()) > MaxAge Then
Deleted = Deleted + 1
WScript.Echo verb & oFile.Path & """"
If Active Then oFile.Delete
End If
Next
if not Recursive then Exit Sub
For Each oSubfolder In oFldr.Subfolders
CheckFolder(oSubfolder)
Next
End Sub

Well, what about this:
Const Active = True
Const sSource = "E:\start_folder" 'or "E:\" but not "E:"
Const MaxAge = 7 'days
Const Recursive = True
Dim dtOld, Checked, Deleted, verb
dtOld = Now - MaxAge
Checked = 0
Deleted = 0
If Active Then verb = "Deleting """ Else verb = "Old file: """
Validate sSource
Cleanup sSource
WScript.Echo
If Active Then verb = " file(s) deleted" Else verb = " file(s) would be deleted"
WScript.Echo Checked & " file(s) checked, " & Deleted & verb
Sub Validate(sFolder)
With CreateObject("Scripting.FileSystemObject")
If Not .FolderExists(sFolder) Then
Err.Raise 76 'Path not found
End If
If .GetFolder(sFolder).IsRootFolder Then
If .GetDrive(.GetDriveName(sFolder)) = _
CreateObject("WScript.Shell").Environment(_
"PROCESS")("HOMEDRIVE") Then
Err.Raise 75 'Path/File access error
End If
End If
End With
End Sub
Sub Cleanup(sFolder)
Dim obj
With CreateObject("Scripting.FileSystemObject").GetFolder(sFolder)
'recurse first
If Recursive Then
For Each obj In .SubFolders
Cleanup obj
Next
End If
'next delete oldest files
For Each obj In .Files
If obj.DateCreated < dtOld Then
Deleted = Deleted + 1
WScript.Echo verb & obj.Path & """"
If Active Then obj.Delete(True)
End If
Next
Checked = Checked + .Files.Count
'and then delete old or empty folders
For Each obj In .SubFolders
If obj.DateCreated < dtOld Or 0 = obj.Size Then
'count here in a variable if you like...
If Active Then obj.Delete(True)
End If
Next
End With
End Sub
P.S. Need to warn about one weak moment. FSO use a snapshot Folders collection, that mean during iteration FSO may try to access folder that no more exists. In other words, made separate procedure for deleting folders.

Related

How to recover the outlook emails for a deleted email account

I accidentally delete my email account and so all of the emails in that account. Is there a chance to recover the emails? How can I recover it? Thanks.
Four months ago I would have agreed with Om3r's comment giving the location of the Outlook stores. But I bought a new laptop in December and now the Outlook files are not where all the documentation says they should be. Worse, I cannot reach the folders containing the Outlook files using File Explorer although I can find them with VBA.
The macro below searches drive C for files with an extension of OST or PST. I cannot promise this macro will find your lost store but, if it is still on your disc, it will find it. If you find the missing store, you will probably have to use VBA to move it to somewhere accessible.
Copy the macro below to a macro-enabled workbook and run it. While it is running the active worksheet will look like:
1923 Folders to search
327 Folders searched
Store Size Date Folder
$ILJARJ0.pst 212 28Mar20 C:\$Recycle.Bin\S-1-5-21-3957073674-21115239-22921093-1001
$IMS96DJ.pst 212 28Mar20 C:\$Recycle.Bin\S-1-5-21-3957073674-21115239-22921093-1001
The top two rows give a crude progress indicator. On my laptop, the routine ends with 69190 folders searched. I do not know why there are PST files in my recycle bin. I did nothing relevant on 28 March. When the routine has finished, there will be a auto-fitted list of every store the macro found. On my laptop none are where I would expect and some are duplicates. I hope you find your store.
Option Explicit
Sub SearchForStoresOnC()
' Searches drive C for files with an extension of PST or OST
' Warning: overwrites the active workbook
Dim ErrNum As Long
Dim FileAttr As Long
Dim FileName As String
Dim FldrName As String
Dim RowCrnt As Long
Dim ToSearch As Collection
Cells.EntireRow.Delete
Range("A1").Value = 0
Range("A2").Value = 0
Range("B1").Value = "Folders to search"
Range("B2").Value = "Folders searched"
Range("B4").Value = "Store"
With Range("C4")
.Value = "Size"
.HorizontalAlignment = xlRight
End With
With Range("D4")
.Value = "Date"
.HorizontalAlignment = xlRight
End With
Range("E4") = "Folder"
RowCrnt = 5
Set ToSearch = New Collection
' Load ToSearch with drive to search.
ToSearch.Add "C:"
Do While ToSearch.Count > 0
FldrName = ToSearch(1)
ToSearch.Remove 1
Err.Clear
ErrNum = 0
On Error Resume Next
' Stores are unlikely to be hidden but can be in folders that are hidden
FileName = Dir$(FldrName & "\*.*", vbDirectory + vbHidden + vbSystem)
ErrNum = Err.Number
On Error GoTo 0
If ErrNum <> 0 Then
'Debug.Print "Dir error: " & FldrName
Else
Do While FileName <> ""
If FileName = "." Or FileName = ".." Then
' Ignore pointers
Else
Err.Clear
On Error Resume Next
FileAttr = GetAttr(FldrName & "\" & FileName)
ErrNum = Err.Number
On Error GoTo 0
If ErrNum = 0 Then
' Ignore file and folders which give errors
If (FileAttr And vbDirectory) = 0 Then
' File
'Debug.Assert False
Select Case Right$(FileName, 4)
Case ".pst", ".ost"
Cells(RowCrnt, "B").Value = FileName
With Cells(RowCrnt, "C")
.Value = FileLen(FldrName & "\" & FileName)
.NumberFormat = "#,##0"
End With
With Cells(RowCrnt, "D")
.Value = FileDateTime(FldrName & "\" & FileName)
.NumberFormat = "dmmmyy"
End With
Cells(RowCrnt, "E").Value = FldrName
RowCrnt = RowCrnt + 1
End Select
Else
' Directory
ToSearch.Add FldrName & "\" & FileName
End If ' File or Directory
Else
'Debug.Print "FileAttr error: " & FldrName & "\" & FileName
End If ' FileAttr does not give an error
End If ' Pointer or (File or Directory)
FileName = Dir$
Loop ' For each pointer, file and sub-directory in folder
End If ' Dir$ gives error
Range("A1") = ToSearch.Count
Range("A2") = Range("A2") + 1
DoEvents
Loop 'until ToSearch empty
Columns.AutoFit
End Sub

Error Handling in VBScript to check for number of files in a folder

I have written a script to check that 4 files exist in a folder. I need to use the below error handling for this particular small piece of code.
This code checks various folders to see if it contains 4 files. If it does then good if it doesn't then its not good.
Code:
Const intOK = 0
Const intCritical = 2
Const intError = 3
Const ForReading=1,ForWriting=2,ForAppending=8
Dim filename,filenamemov,emailaddr
Dim arrFolders(17)
Dim argcountcommand,dteToday
Dim arg(4)
Dim strMailServer,Verbose,strExt,numfiles,intIndex
Dim intcount : intCount = 0
Dim stroutput
numfiles = 4 'how many minutes old are the files
Verbose = 0 '1 FOR DEBUG MODE, 0 FOR SILENT MODE
arrFolders(0) = "D:\AS2\Inbound\WESSEX"
arrFolders(1) = "D:\AS2\Inbound\EATWELL"
arrFolders(2) = "D:\AS2\Inbound\TURNER\"
For intIndex = 0 To UBound(arrFolders)
pt "Checking folder: " & arrFolders(intIndex)
If arrFolders(intIndex) = "" Then
pt "Empty folder value!"
Exit For
Else
Call checkfiles(arrFolders(intIndex))
End If
Next
If objFolder.Files.Count < 4 Then
WScript.Echo "CRITICAL - " & intCount & " File(s) over " & numfiles & "
minutes in " & stroutput
WScript.Quit(intCritical)
Else
WScript.Echo "OK - No directory contains less than 4 files"
WScript.Quit(intOK)
End If
Sub checkfiles(folderspec)
'check If any files exist on folder
On Error Resume Next
Dim objFso : Set objFso = CreateObject("Scripting.FileSystemObject")
'you can take this as input too using InputBox
'this will error If less than 4 files exist.
Dim objFolder : Set objFolder = objFso.GetFolder(strFolderPath)
If objfolder.Files.Count = 4 Then
MsgBox "This is Correct"
Else
MsgBox "This isnt Correct"
End If
Sub pt(txt)
If Verbose = 1 Then
WScript.Echo txt
End If
End Sub
If i understand your question, you want to
check a set of folders kept in an array for the number of files they contain
if any of the folders has less than 4 files, an error message should be displayed
the folder array CAN contain empty values and the routine should skip those
Apparently you have more plans considering all 'extra' variables you have in your code like Const ForReading=1,ForWriting=2,ForAppending=8 and Dim filename,filenamemov,emailaddr, but I left them out here, because they have nothing to do with the question at hand.
Option Explicit
Const intOK = 0
Const intCritical = 2
Const intError = 3
Dim Verbose, path, fileCount, minCount, intCount, errCount
Dim objFso, objFolder, intResult, strResult
Verbose = 0 '1 FOR DEBUG MODE, 0 FOR SILENT MODE
minCount = 4 'The minimal number of files each folder should have
Dim arrFolders(17)
arrFolders(0) = "D:\AS2\Inbound\WESSEX"
arrFolders(1) = "D:\AS2\Inbound\EATWELL"
arrFolders(2) = "D:\AS2\Inbound\TURNER\"
Set objFso = CreateObject("Scripting.FileSystemObject")
intResult = intOK 'assume all is well
strResult = "" 'to accumulate critical errors for each folder
intCount = 0 'the total running count of folders we have checked
errCount = 0 'the total count of errors (folders with less than 4 files) we have found
For Each path In arrFolders
If Len(path) > 0 Then
intCount = intCount + 1
WScript.Echo "Checking folder: " & path
Set objFolder = objFso.GetFolder(path)
fileCount = objfolder.Files.Count
'considering the "OK - No directory contains less than 4 files" message
'in your original post, this test needs to do a 'Greater Than Or Equal To', so use >=
If fileCount >= minCount Then
WScript.Echo "This is correct: " & path
Else
WScript.Echo "This is NOT correct: " & path
strResult = strResult & vbNewLine & "CRITICAL - " & fileCount & " File(s) in folder " & path
intResult = intCritical
errCount = errCount + 1
End If
End if
Next
'clean up used objects
Set objFolder = Nothing
Set objFso = Nothing
If errCount > 0 Then
'we have folders with errors
WScript.Echo strResult
Else
'This message implies that a folder is also 'Good' when more than 4 files exist
WScript.Echo "OK - All " & intCount & " directories contain at least " & minCount & " files"
End If
WScript.Quit(intResult)

Identify and Copy latest files in directory

Everyday around 7 AM there are 3 csv exports extracted into a specific folder and the file names are exactly the same each day except everyday the prefix of the file name is amended to the current date.
Example:
16-02-2018_Test1 will change to 17-02-2018_Test1
16-02-2018_Test2 will change to 17-02-2018_Test2
16-02-2018_Test3 will change to 17-02-2018_Test3
The file itself is not replaced, the new file with the current date is instead added to this folder.
What I need to do is identify the 3 extracts each day and copy them to a sub-folder. The best way I thought of doing this is by identifying the date at which the file was last modified.
I have the below VBS code I found and helps identifies the latest file in a directory and I added a line that will copy that file to a new directory.
The issue however, is that the code only identifies 1 file instead of 3 and I can only copy 1 file instead of 3. If anyone has better code to help me achieve the desired result or alternatively can help modify the existing code to achieve the desired result.
sPath = "C:\Users\Desktop\Test\"
Const sToDir = "C:\Users\Desktop\Test\NewFolder\"
Set oFSO = CreateObject("Scripting.FileSystemObject")
sNewestFile = GetNewestFile(sPath)
If sNewestFile <> "" Then
WScript.Echo "Newest file is " & sNewestFile
dFileModDate = oFSO.GetFile(sNewestFile).DateLastModified
If DateDiff("n", dFileModDate, Now) > 60 Then
oFSO.CopyFile sNewestFile, sToDir
End If
Else
WScript.Echo "Directory is empty"
End If
Function GetNewestFile(ByVal sPath)
sNewestFile = Null ' init value
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(sPath)
Set oFiles = oFolder.Files
' enumerate the files in the folder, finding the newest file
For Each oFile In oFiles
On Error Resume Next
If IsNull(sNewestFile) Then
sNewestFile = oFile.Path
dPrevDate = oFile.DateLastModified
Elseif dPrevDate < oFile.DateLastModified Then
sNewestFile = oFile.Path
dPrevDate = oFile.DateLastModified
End If
On Error Goto 0
Next
If IsNull(sNewestFile) Then sNewestFile = ""
GetNewestFile = sNewestFile
End Function
Invest some work in a useful format class and
just look for the 3 files of the day (FileExists)
if they are not there, look for the previous day's files
or
search for the newest file and build all three file names from the prefix
In code:
Option Explicit
' stolen from https://stackoverflow.com/a/21643663/603855
' added formatTwo; left as exercise: formatThree
Class cFormat
Private m_oSB
Private Sub Class_Initialize()
Set m_oSB = CreateObject("System.Text.StringBuilder")
End Sub ' Class_Initialize
Public Function formatOne(sFmt, vElm)
m_oSB.AppendFormat sFmt, vElm
formatOne = m_oSB.ToString()
m_oSB.Length = 0
End Function ' formatOne
Public Function formatTwo(sFmt, vElm1, vElm2)
m_oSB.AppendFormat_2 sFmt, vElm1, vElm2
formatTwo = m_oSB.ToString()
m_oSB.Length = 0
End Function ' formatOne
Public Function formatArray(sFmt, aElms)
m_oSB.AppendFormat_4 sFmt, (aElms)
formatArray = m_oSB.ToString()
m_oSB.Length = 0
End Function ' formatArray
End Class ' cFormat
Dim oFmt : Set oFmt = New cFormat
Dim sFmt : sFmt = "{0:dd-MM-yyyy}_Test{1}"
Dim dToday : dToday = Date()
Dim i
WScript.Echo "file names expected today " & oFmt.formatOne("({0:yyyy-MMM-d}).", dToday)
For i = 1 To 3
WScript.Echo oFmt.FormatTwo(sFmt, dToday, i)
Next
WScript.Echo oFmt.formatArray("look for {0} if {1} is missing on the {2:dd}th after 7 AM" _
, Array(oFmt.FormatTwo(sFmt, DateAdd("d", -1, dToday), 1), oFmt.FormatTwo(sFmt, dToday, 1), dToday))
Dim sFnd : sFnd = oFmt.FormatTwo(sFmt, dToday, 2)
WScript.Echo "if your GetNewestFile() finds " & sFnd & ", copy:"
For i = 1 To 3
WScript.Echo Left(sFnd, Len(sFnd) - 1) & i
Next
output:
cscript 48866113.vbs
file names expected today (2018-Feb-19).
19-02-2018_Test1
19-02-2018_Test2
19-02-2018_Test3
look for 18-02-2018_Test1 if 19-02-2018_Test1 is missing on the 19th after 7 AM
if your GetNewestFile() finds 19-02-2018_Test4, copy:
19-02-2018_Test1
19-02-2018_Test2
19-02-2018_Test3
Thanks to everyone for the help, I found the answer on a different thread. Here is the link: Copy 2 latest text file from a source folder to destination folder
Below is the code:
Option Explicit
Dim FolderToCheck, FolderDestination, FileExt, mostRecent, noFiles, fso, fileList, file, filecounter, oShell, strHomeFolder
' Enumerate current user's home path - we will use that by default later if nothing specified in commandline
Set oShell = CreateObject("WScript.Shell")
strHomeFolder = oShell.ExpandEnvironmentStrings("%USERPROFILE%")
'Variables -----
folderToCheck = strHomeFolder & "\Desktop\MY\MMS" ' Folder Source to check for recent files to copy FROM
folderDestination = strHomeFolder & "\Desktop\New" ' Destination Folder where to copy files TO
fileExt = "txt" ' Extension we are searching for
mostRecent = 2 ' Most Recent number of files to copy
' --------------
PreProcessing() ' Retrieve Command Line Parameters
' Display what we are intending on doing
wscript.echo "Checking Source: " & FolderToCheck
wscript.echo "For Files of type: " & FileExt
wscript.echo "Copying most recent "& mostRecent &" file(s) to: " & FolderDestination & "."
wscript.echo
noFiles = TRUE
Set fso = CreateObject("Scripting.FileSystemObject")
Set fileList = CreateObject("ADOR.Recordset")
fileList.Fields.append "name", 200, 255
fileList.Fields.Append "date", 7
fileList.Open
If fso.FolderExists(FolderToCheck) Then
For Each file In fso.GetFolder(FolderToCheck).files
If LCase(fso.GetExtensionName(file)) = LCase(FileExt) then
fileList.AddNew
fileList("name").Value = File.Path
fileList("date").Value = File.DateLastModified
fileList.Update
If noFiles Then noFiles = FALSE
End If
Next
If Not(noFiles) Then
wscript.echo fileList.recordCount & " File(s) found. Sorting and copying last " & mostRecent &"..."
fileList.Sort = "date DESC"
If Not(fileList.EOF) Then
fileList.MoveFirst
If fileList.recordCount < mostRecent Then
wscript.echo "WARNING: " & mostRecent &" file(s) specified but only " & fileList.recordcount & " file(s) match criteria. Adjusted to " & fileList.RecordCount & "."
mostRecent = fileList.recordcount
End If
fileCounter = 0
Do Until fileList.EOF Or fileCounter => mostRecent
If Not(fso.FolderExists(folderDestination)) Then
wscript.echo "Destination Folder did not exist. Creating..."
fso.createFolder folderDestination
End If
fso.copyfile fileList("name"), folderDestination & "\", True
wscript.echo fileList("date").value & vbTab & fileList("name")
fileList.moveNext
fileCounter = fileCounter + 1
Loop
Else
wscript.echo "An unexpected error has occured."
End If
Else
wscript.echo "No matching """ & FileExt &""" files were found in """ & foldertocheck & """ to copy."
End If
Else
wscript.echo "Error: Source folder does not exist """ & foldertocheck & """."
End If
fileList.Close
Function PreProcessing
Dim source, destination, ext, recent
' Initialize some variables
Set source = Nothing
Set destination = Nothing
Set ext = Nothing
Set recent = Nothing
'Get Command Line arguments
' <scriptname>.vbs /Source:"C:\somepath\somefolder" /Destination:"C:\someotherpath\somefolder" /ext:txt /recent:2
source = wscript.arguments.Named.Item("source")
destination = wscript.arguments.Named.Item("destination")
ext = wscript.arguments.Named.Item("ext")
recent = wscript.arguments.Named.Item("recent")
If source <> "" Then FolderToCheck = source
If destination <> "" Then FolderDestination = destination
If ext <> "" Then FileExt = ext
If recent <> "" Then mostRecent = int(recent)
End Function

VBAScript to delete items from folder

I'm new to VBScripting and have completely no knowledge on how to code but however i understand the basics of VBScripting.
I tried using the search function to find similar cases to mine but it doesn't have what i need.
I would really appreciate any help as my project is due soon.
Scenario:
I need to delete jpeg files that are more than 3months old that is in a directory with lots and lots of subfolders within each other. Furthermore there are 4 folders in the directory that i must not delete or modify.
How i manually did it was to navigate to the mapped drive, to the folder, use the "Search 'Folder'" from the window and type in this "datemodified:‎2006-‎01-‎01 .. ‎2013-‎08-‎31".
It will then show all the folders and subfolders and excel sheets within that folder, i'll then filter the shown list by ticking jpeg only from Type.
Code:
'**** Start of Code **********
Option Explicit
On Error Resume Next
Dim oFSO, oFolder, sDirectoryPath
Dim oFileCollection, oFile, sDir
Dim iDaysOld
' Specify Directory Path From Where You want to clear the old files
sDirectoryPath = "C:\MyFolder"
' Specify Number of Days Old File to Delete
iDaysOld = 15
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(sDirectoryPath)
Set oFileCollection = oFolder.Files
For each oFile in oFileCollection
'This section will filter the log file as I have used for for test case
'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), 4)) = "jpeg" Then
If oFile.DateLastModified < (Date() - iDaysOld) Then
oFile.Delete(True)
End If
End If
Next
Set oFSO = Nothing
enter code here`Set oFolder = Nothing
enter code here`Set oFileCollection = Nothing
enter code here`Set oFile = Nothing
'******* End of Code **********
I need to set an path that must be excluded + go through sub folders.
I'd like to thank you in advance for helping me out.
Thanks,
Working solution (Jobbo almost got it to work in generic form):
UPDATE: includes log file writing with number of folders skipped and files deleted.
Option Explicit
'set these constants to your requirements
Const DIR = "C:\Test"
Const LOGFILE = "C:\Log.txt" ' Location of Log file
Const MAX_AGE = 3 ' Unit: Months
Const FILEEXT = "jpeg"
Dim oFSO
Dim oLogFile
Dim aExclude
Dim lngDeletes, lngSkips
'add to this array to exclude paths
aExclude = Array("c:\Test\test 1", "c:\Test\test 2\test")
Set oFSO = CreateObject("Scripting.FilesystemObject")
Set oLogFile = oFSO.createtextfile(LOGFILE)
lngDeletes = 0
lngSkips = 0
LOGG "Script Start time: " & Now
LOGG "Root Folder: " & DIR
LOGG String(50, "-")
deleteFiles oFSO.GetFolder(DIR)
LOGG String(50, "-")
LOGG lngDeletes & " files are deleted"
LOGG lngSkips & " folders skipped"
LOGG "Script End time: " & Now
oLogFile.Close
Set oLogFile = Nothing
Set oFSO = Nothing
MsgBox "Logfile: """ & LOGFILE & """", vbInformation, wscript.scriptName & " Completed at " & Now
wscript.Quit
'=================================
Sub LOGG(sText)
oLogFile.writeline sText
End Sub
'=================================
Function isExclude(sPath)
Dim s, bAns
bAns = False
For Each s In aExclude
If InStr(1, sPath, s, vbTextCompare) = 1 Then
bAns = True
Exit For
End If
Next
isExclude = bAns
End Function
'=================================
Function isOldFile(fFile)
' Old file if "MAX_AGE" months before today is greater than the file modification time
isOldFile = (DateAdd("m", -MAX_AGE, Date) > fFile.DateLastModified)
End Function
'==================================
Function isFileJPEG(fFile)
Dim sFileName
sFileName = fFile.Name
' Mid(sFileName, InStrRev(sFileName, ".")) gives you the extension with the "."
isFileJPEG = (LCase(Mid(sFileName, InStrRev(sFileName, ".") + 1)) = FILEEXT)
End Function
'==================================
Sub deleteFiles(fFolder)
Dim fFile, fSubFolder
If Not isExclude(fFolder.Path) Then
'WScript.echo "==>> """ & fFolder.Path & """" ' Comment for no output
For Each fFile In fFolder.Files
If isFileJPEG(fFile) And isOldFile(fFile) Then
lngDeletes = lngDeletes + 1
LOGG lngDeletes & vbTab & fFile.Path
'WScript.echo vbTab & "DELETE: """ & fFile.Path & """" ' Comment for no output
fFile.Delete True ' Uncomment to really delete the file
End If
Next
' Only Process sub folders if current folder is not excluded
For Each fSubFolder In fFolder.SubFolders
deleteFiles fSubFolder
Next
Else
lngSkips = lngSkips + 1
'WScript.echo "<<-- """ & fFolder.Path & """" ' Comment for no output
End If
End Sub
Never ever use On Error Resume Next unless it absolutely cannot be avoided.
This problem needs a recursive function. Here's how I would do it:
Option Explicit
'set these constants to your requirements
Const DIR = "C:\MyFolder"
Const AGE = 15
Dim oFSO
Dim aExclude
'add to this array to exclude paths
aExclude = Array("c:\folder\exclude1", "c:\folder\another\exclude2")
Set oFSO = CreateObject("Scripting.FilesystemObject")
Call deleteFiles(oFSO.GetFolder(DIR))
Set oFSO = Nothing
WScript.Quit
'=================================
Function isExclude(sPath)
Dim s
For Each s in aExclude
If LCase(s) = LCase(sPath) Then
isExclude = True
Exit Function
End If
Next
isExclude = False
End Function
'==================================
Sub deleteFiles(fFolder)
Dim fFile, fSubFolder
If Not isExclude(fFolder.Path) Then
For Each fFile in fFolder.Files
If (LCase(Right(Cstr(fFile.Name),4)) = "jpeg") And (fFile.DateLastModified < (Date() - AGE)) Then
'WScript.echo fFile.Path 'I put this in for testing, uncomment to do the same
Call fFile.Delete(true)
End If
Next
End If
For Each fSubFolder in fFolder.SubFolders
Call deleteFiles(fSubFolder)
Next
End Sub
I'm not really able to fully test it out because I don't have an example data set, but really all you need to do is set DIR and change the aExclude array. Make sure you know what its going to delete before you run it though...
Also, it will only delete jpeg extensions, not jpg but I imagine you already know that

Extract files from ZIP file with VBScript

When extracting files from a ZIP file I was using the following.
Sub Unzip(strFile)
' This routine unzips a file. NOTE: The files are extracted to a folder '
' in the same location using the name of the file minus the extension. '
' EX. C:\Test.zip will be extracted to C:\Test '
'strFile (String) = Full path and filename of the file to be unzipped. '
Dim arrFile
arrFile = Split(strFile, ".")
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CreateFolder(arrFile(0) & "\ ")
pathToZipFile= arrFile(0) & ".zip"
extractTo= arrFile(0) & "\ "
set objShell = CreateObject("Shell.Application")
set filesInzip=objShell.NameSpace(pathToZipFile).items
objShell.NameSpace(extractTo).CopyHere(filesInzip)
fso.DeleteFile pathToZipFile, True
Set fso = Nothing
Set objShell = Nothing
End Sub 'Unzip
This was working, but now I get a "The File Exists" Error.
What is the reason for this? Are there any alternatives?
All above solutions are accurate, but they are not definitive.
If you are trying to extract a zipped file into a temporary folder, a folder that displays "Temporary Folder For YOURFILE.zip" will immediately be created (in C:\Documents and Settings\USERNAME\Local Settings\Temp) for EACH FILE contained within your ZIP file, which you are trying to extract.
That's right, if you have 50 files, it will create 50 folders within your temp directory.
But if you have 200 files, it will stop at 99 and crash stating - The File Exists.
..
Apparently, this does not occur on Windows 7 with the contributions I view above. But regardless, we can still have checks. Alright, so this is how you fix it:
'========================
'Sub: UnzipFiles
'Language: vbscript
'Usage: UnzipFiles("C:\dir", "extract.zip")
'Definition: UnzipFiles([Directory where zip is located & where files will be extracted], [zip file name])
'========================
Sub UnzipFiles(folder, file)
Dim sa, filesInzip, zfile, fso, i : i = 1
Set sa = CreateObject("Shell.Application")
Set filesInzip=sa.NameSpace(folder&file).items
For Each zfile In filesInzip
If Not fso.FileExists(folder & zfile) Then
sa.NameSpace(folder).CopyHere(zfile), &H100
i = i + 1
End If
If i = 99 Then
zCleanup(file, i)
i = 1
End If
Next
If i > 1 Then
zCleanup(file, i)
End If
fso.DeleteFile(folder&file)
End Sub
'========================
'Sub: zCleanup
'Language: vbscript
'Usage: zCleanup("filename.zip", 4)
'Definition: zCleanup([Filename of Zip previously extracted], [Number of files within zip container])
'========================
Sub zCleanUp(file, count)
'Clean up
Dim i, fso
Set fso = CreateObject("Scripting.FileSystemObject")
For i = 1 To count
If fso.FolderExists(fso.GetSpecialFolder(2) & "\Temporary Directory " & i & " for " & file) = True Then
text = fso.DeleteFolder(fso.GetSpecialFolder(2) & "\Temporary Directory " & i & " for " & file, True)
Else
Exit For
End If
Next
End Sub
And that's it, copy and paste those two functions into your VBScript hosted program and you should be good to go, on Windows XP & Windows 7.
Thanks!
You can use DotNetZip from VBScript.
To unpack an existing zipfile, overwriting any files that may exist:
WScript.echo("Instantiating a ZipFile object...")
Dim zip
Set zip = CreateObject("Ionic.Zip.ZipFile")
WScript.echo("Initialize (Read)...")
zip.Initialize("C:\Temp\ZipFile-created-from-VBScript.zip")
WScript.echo("setting the password for extraction...")
zip.Password = "This is the Password."
' set the default action for extracting an existing file
' 0 = throw exception
' 1 = overwrite silently
' 2 = don't overwrite (silently)
' 3 = invoke the ExtractProgress event
zip.ExtractExistingFile = 1
WScript.echo("extracting all files...")
Call zip.ExtractAll("extract")
WScript.echo("Disposing...")
zip.Dispose()
WScript.echo("Done.")
To create a new zipfile:
dim filename
filename = "C:\temp\ZipFile-created-from-VBScript.zip"
WScript.echo("Instantiating a ZipFile object...")
dim zip2
set zip2 = CreateObject("Ionic.Zip.ZipFile")
WScript.echo("using AES256 encryption...")
zip2.Encryption = 3
WScript.echo("setting the password...")
zip2.Password = "This is the Password."
WScript.echo("adding a selection of files...")
zip2.AddSelectedFiles("*.js")
zip2.AddSelectedFiles("*.vbs")
WScript.echo("setting the save name...")
zip2.Name = filename
WScript.echo("Saving...")
zip2.Save()
WScript.echo("Disposing...")
zip2.Dispose()
WScript.echo("Done.")
There's answers above which are perfectly correct, but I thought I'd wrap everything up into a full solution that I'm using:
strZipFile = "test.zip" 'name of zip file
outFolder = "." 'destination folder of unzipped files (must exist)
'If using full paths rather than relative to the script, comment the next line
pwd = Replace(WScript.ScriptFullName, WScript.ScriptName, "")
Set objShell = CreateObject( "Shell.Application" )
Set objSource = objShell.NameSpace(pwd+strZipFile).Items()
Set objTarget = objShell.NameSpace(pwd+outFolder)
intOptions = 256
objTarget.CopyHere objSource, intOptions
'Clean up
Set WshShell = CreateObject("Wscript.Shell")
tempfolder = WshShell.ExpandEnvironmentStrings("%temp%")
Set fso = CreateObject("Scripting.FileSystemObject")
Call fso.DeleteFolder(tempfolder + "\Temporary Directory 1 for " + strZipFile, True )
http://www.experts-exchange.com/Programming/Languages/Visual_Basic/VB_Script/Q_23022290.html
Check your temp directory. If you have 99 folders associated with this unzipping process, try deleting them.
I added the following code to the beginning of my unzip procedure to delete these directories before I unzip:
For i = 1 To 99
If aqFileSystem.Exists(GetAppPath("Local Settings", "") & "\Temp\Temporary Directory " & i & " for DialogState.zip") = True Then
result = aqFileSystem.ChangeAttributes(GetAppPath("Local Settings", "") & "\Temp\Temporary Directory " & i & " for DialogState.zip", 1 OR 2, aqFileSystem.fattrFree)
Call DelFolder(GetAppPath("Local Settings", "") & "\Temp\Temporary Directory " & i & " for DialogState.zip")
Else
Exit For
End If
Next

Resources