TheGeekery

The Usual Tech Ramblings

Quick Windows Scripting

We have a small issue in one of our products, which will be fixed in the next release. When you login, it generates an “overview” chart (4 of them actually), and writes them to disk, and displays them to the user. The problem comes when they don’t clean up. Because the code first checks if the file exists before writing it, it scans the directory. This would normally be okay, on a physical server, with fast disks. However, these are virtual boxes, with “fake” disks. I/O is terrible on virtual servers, so when there are about 6,000 images in that folder, the box dies a slow and painful death every time somebody logs in. So I had to figure an easy way around it. Linux would have made this task a one-liner.

find . -type f -iname '*.jpg' -amin +1 -exec rm {} \;

This code finds all files with a jpg extension, that was last accessed over a minute ago, then deletes it. Windows on the other hand doesn’t have a nice shell command like this, so I got stuck with vbs, and WMI. I ended up with the following script:

Option Explicit
dim oFileSys, dir, oFiles, oFile, dCreated, fDateInfo, iAge, oFolder

dir = "D:\<folder>\Charts\"

 
Set oFileSys = CreateObject("Scripting.FileSystemObject")
set oFolder = oFileSys.GetFolder(dir)
set oFiles = oFolder.Files

for each oFile in oFiles
  Set fDateInfo = oFileSys.GetFile(oFile)
  dCreated = fDateInfo.DateCreated
  iAge = DateDiff("n", dCreated, Now)
  if iAge > 1 then
    oFile.Delete
  End If
Next

So windows takes my one-liner linux code, and makes it 14 lines (not counting blank lines). I’ve now got this setup to run once a minute, and it cleans up the older images in that folder.

Comments