VBScript to delete files

Status
Not open for further replies.

Digitlman

Ars Tribunus Militum
2,434
I found a VB script to delete files in a dir older than a certain date:

Option Explicit

‘ Path to delete
const FolderName ="c:\Temp"
‘ Age of file (last modified) in days before it is deleted
const Days=7

‘Set debug to 1 for screen pops with helpful messages
const debugmode=0

const SUCCESS=0
const ERROR=1
const WARNING=2
const INFORMATION=4
dim result
logit "Begining process to delete temp files in " & FolderName & " older than " & Days & " Days",INFORMATION
result = delFiles(FolderName,Days)

Function delFiles(strDir,strDays)
‘ Take in the path to delete and the number of days old a file has to be
‘ Then delete the files in that path if they are older than that date

dim fso,file,folder,individualFile,foldercontains
dim strComments
dim intDeleted, intNotDeleted
intDeleted=0
intNotDeleted=0
Set fso = CreateObject("Scripting.FileSystemObject")
on error resume next

Set folder = fso.GetFolder(strDir)
if err = 0 then
strComments = strComments & strDir & " exists." & VBCRLF
else
strComments = strComments & ". **ERROR** Accessing folder – cannot find " & strDir & VBCRLF & err.description & " (" & err.source & ")" & VBCRLF

intNotDeleted=intNotDeleted+1
end if
err.Clear

Set foldercontains = folder.Files
dim intDifferenceinDays
strComments = strComments & "Deleting Files older than " & strDays & " days" & VBCRLF
For Each individualFile in folderContains
‘ Loop through each file in the folder and check its date
if debugmode=1 then
wscript.echo ("Looking at " & individualfile & VBCRLF & "Which has date last modified of: " & individualFile.datelastmodified _

& VBCRLF & "To see if its " & strDays & " days older than " & Now)
End if
strComments = strComments & VBCRLF & "Analysed " & individualfile & ": "
intDifferenceinDays = DateDiff("d", individualFile.datelastmodified, Now)
If intDifferenceinDays > strDays Then
if debugmode=1 then
wscript.echo ("We’ve decided to delete" & file &"… Datediff is" & intDifferenceinDays )
End if
strComments = strComments & " Deleting…."
on error resume next
fso.DeleteFile individualFile,TRUE
if err = 0 then
intDeleted=intDeleted+1
strComments = strComments & ". SUCCESS"
else
intNotDeleted=intNotDeleted+1
strComments = strComments & ". **ERROR** " & err.description & " (" & err.source & ")"
end if
err.Clear
Else
if debugmode=1 then
wscript.echo ("We’ve decided to spare" & file &"… DiD: " & intDifferenceinDays & " Required: " & strDays)

End if
strComments = strComments & "Not Deleted. Only " & intDifferenceinDays & " days old"
End If
Next
strComments = strComments & VBCRLF & "No of Files Deleted: " & intDeleted & VBCRLF & "ERROR in deleting: " & intNotDeleted

if intNotDeleted > 0 then
logit strComments, ERROR
else
logit strComments,INFORMATION
end if
delFiles=1
End Function

Function logit(text,level)
‘ Writes a simple message to the windows event log
dim Wshshell
set WshShell = CreateObject("WScript.Shell")
WshShell.LogEvent level, text
logit=1

end Function


However, when I try and run this a "test.vbs", I get an invalid character on the "'" comment character, and I cannot determine why.
 

Digitlman

Ars Tribunus Militum
2,434
Well, it seems to be working, kinda.

When I place point it to a dir with over 400 items in it, it says that is is checking, but 10 mins later it looks like nothing is happening.

When I run it in debug, I get a popup on every file it is looking at.

How can I verify it is working while not in debug mode? When I run in debug, the wsh.exe is running in the user space while the pop ups are working. Non-debug mode....not so much.
 

TheBorg

Ars Tribunus Angusticlavius
8,555
If it's popping up dialogs it means WSH's default interaction mode is Windows (via wscript). You have a couple of options to run your script with a command line interface (aka cscript):

1. Instead of running it as "deletefiles.vbs", run it as "cscript.exe deletefiles.vbs".
2. Change the default mode to comand line by running "cscript.exe //H:CScript" once, then you can go back to running "deletefiles.vbs".

edit: clarified stuff
 

TheBorg

Ars Tribunus Angusticlavius
8,555
Further to what JJJ is saying:

Always be suspicious when downloading source code until you've analyzed it and thoroughly understand it. For example, there's a possibility that this script could go haywire and delete files willy nilly, especially if it's ignoring the readonly attribute. I usually try and learn what it's doing and apply it to my issue rather than use the whole thing. Your mileage may vary. I think you got it from here - http://colinchaplin.wordpress.com/2010/ ... -few-days/ - and even the author freely admits it's not necessarily solid, so caveat emptor!

At any rate, I think I found the next thing for you to check. Here's what I did:

1. Cleaned up the single quotes per above.
2. Ran the script in debug mode as follows: cscript.exe //x test_script.vbs. But before it even ran it returned an error:

test_script.vbs(48, 1) Microsoft VBScript compilation error: Expected ')'

If you look at line 48 it appears that there's a blank line separating a long line of code with a "_" separator. Remove the blank line and it will at least let you proceed.

I don't have time right now to keep going with it, but here are a couple of suggestions:

a. Remove the "on error resume next" commands.
b. Convert the writes to the event log to "wscript.echo", so you can see it in the command window.
c. If you have Visual Studio (the Express editions are free from Microsoft) then running it with the //x argument as I did above will pop up the VS just-in-time debugger, and you can then step through it line by line, look at variables, etc.
d. Start from scratch: create a new script and build it up a little bit at a time.

Good luck!
 

TheBorg

Ars Tribunus Angusticlavius
8,555
One other note: the little I did look at the code I found what I think are wonky design decisions - check out this chunk of code which checks to see if the folder is accessible:

Code:
Set folder = fso.GetFolder(strDir) 
if err = 0 then 
   strComments = strComments & strDir & " exists." & VBCRLF 
else 
   strComments = strComments & ". **ERROR** Accessing folder – cannot find " & strDir & VBCRLF & err.description & " (" & err.source & ")" & VBCRLF 
   intNotDeleted=intNotDeleted+1 
end if 
err.Clear

Maybe it's going over my head, but it seems that no matter what happens, the logic flow is going to advance to the next section which does a "Set foldercontains = folder.Files" before iterating through the files in the potentially inaccessible folder). To me that's not very tidy and a warning flag to be suspicious of the rest of it.
 

TheBorg

Ars Tribunus Angusticlavius
8,555
At the risk of replacing one untrustworthy script with another, here's a lite version of an old script I once wrote - hopefully it's easy to understand:

Code:
dim fso
Set fso = CreateObject("Scripting.FileSystemObject")

Dim DeletedFiles
DeletedFiles = DeleteOldFiles("d",7,"c:\temp\deltest\",true)
wscript.echo "The following files were deleted:"
wscript.echo DeletedFiles
wscript.quit

Private Function DeleteOldFiles(Interval, Age, TargetPath,IncludeSubFolders)
  ' Deletes "old" files, returns back the list. 
  '
  ' Interval: valid interval used by DateDiff function. See http://msdn.microsoft.com/en-us/library/xhtyw595(VS.85).aspx for details.
  ' Age: numeric value
  ' IncludeSubfolders: recursively checks all subfolders
  '
  ' Example:
  ' DeleteOldFiles("d",30,"c:\temp",true)

  dim tempList
  dim theFile
  dim theSubFolder

  tempList = ""
  if fso.FolderExists(targetpath) then
    if IncludeSubfolders = true then
	  for each theSubfolder in fso.getFolder(TargetPath).SubFolders
	  templist = templist & DeleteOldFiles(Interval,Age, thesubfolder.path,IncludeSubfolders)
	next
    end if
    for each theFile in fso.getFolder(targetPath).Files
      if DateDiff(interval,theFile.DateLastModified,Now) >= age then
        tempList = tempList & theFile.DateLastModified & "  " & thefile.path & "\" & theFile.Name & vbcrlf
        ' Note: comment out the next line for debugging
        'theFile.delete
        ' Note: comment out the next line for production use
        wscript.echo "Debug: Would delete file " & thefile.path & "\" & thefile.name 
      end if
    next
  else
    templist = templist & "Path " & TargetPath & " not found."
  end if
  DeleteOldFiles = tempList
End Function

The full version includes the ability to pass arguments into it for interval, age, etc., but it's a bit uglier to look at.

Note the comments where the "TheFile.delete" command is - it allows you to safely test it, and I suggest you test the heck out of it before letting it into productive use.

Note also that I stripped out some of the error checking to improve clarity, like if the script runs into an "Access Denied" situation. It won't be hard to add in the "on error resume next" statements back in.
 
Status
Not open for further replies.