September 26th, 2005

How Can I Delete Specific Files in a Specific Folder?

Hey, Scripting Guy! Question

Hey, Scripting Guy! How can I access the files in the folder T:\Act and delete any files that have the string “current” somewhere in the file name?

— SC

SpacerHey, Scripting Guy! AnswerScript Center

Hey, SC. We have to admit, the notion of deleting anything current has a certain appeal, doesn’t it? Well, not for the Scripting Guys, of course; after all, our lives are so perfect there isn’t anything we’d want to get rid of. OK, maybe car payments. And mortgages. And that dog two houses down who still barks like crazy any time he sees us. (It’s been 10 years, dog; surely you must be used to us by now.)

But that’s about it. Maybe – no, definitely – the old guy around the corner who’s always outside without his shirt on. Oh, and – well, maybe we better focus on deleting all the files that have the string current somewhere in the file name:

strComputer = “.”

Set objWMIService = GetObject(“winmgmts:\\” & strComputer & “\root\cimv2”)

Set colFileList = objWMIService.ExecQuery _ (“ASSOCIATORS OF {Win32_Directory.Name=’T:\Act’} Where ” _ & “ResultClass = CIM_DataFile”)

For Each objFile In colFileList If InStr(objFile.FileName, “current”) Then objFile.Delete End If Next

This script starts out – as many of our WMI scripts do – by binding to the WMI service on the local computer. (Of course, like most WMI scripts, this one can also be run against a remote computer.) We then use this query to return a collection of all the files in the folder T:\Act:

Set colFileList = objWMIService.ExecQuery _
    (“ASSOCIATORS OF {Win32_Directory.Name=’T:\Act’} Where ” _
        & “ResultClass = CIM_DataFile”)

Next we set up a For Each loop in order to walk through the collection of files. Inside that loop we use the InStr function to determine whether or not the string current can be found in the file name:

If InStr(objFile.FileName, “current”) Then

If InStr is True that means that the string can, indeed, be found within the file name. In that case, we use a single line of code to delete the file:

objFile.Delete

Yep: it’s that easy. We then loop around and repeat the process with the next file in the collection. By the time we’re done any file in T:\Act that had the string current in its file name will have gone to that great hard disk in the sky.

Or, to put it in terms that actually make sense, those files will have been deleted.

Now if we could just do the same thing with that dumb orange car – it doesn’t even have a hood! – that the neighbors have parked outside the house. And those blackberry bushes that keep trying to take over the yard. And ….

Author

0 comments

Discussion are closed.