Hey, Scripting Guy! How Can I Return a List of All the Folders Whose Name Starts With a Specified String Value?

Hey, Scripting Guy! Question

Hey, Scripting Guy! How can I find all the folders that start with a specific string? For example, given the string 123 the script would find folders 123000 through 123999.

— MD

SpacerHey, Scripting Guy! AnswerScript Center

Hey, MD. Here in the US we’re still busy trying to figure out who’s going to run for President. (Figure out who will actually be President? We’re still several months away from doing that.) We mention this because, at the conclusion of the 2008 Winter Scripting Games, we received an email that closed with this question:

Dr. Scripto for President?

As far as we know, Dr. Scripto has no plans to run for President; even if he did, the Scripting Guys would strongly discourage him from doing so. No one likes Dr. Scripto more than we do; nevertheless, we not only don’t believe he is qualified to be President, we don’t even believe he is qualified to be a candidate for President. And, trust us: in the US everyone thinks they’re qualified to be a candidate for President.

So why are we so down on Dr. Scripto and his qualifications for being President? Here are a few reasons we came up with off the top of our heads:

Dr. Scripto is not a real person. Granted, many people have made the same claim about former President William Howard Taft. But, still ….

Dr. Scripto is not a well-rounded person. He is, at best, two-dimensional. (Well, unless you count his bobblehead. Which we probably have to do, seeing as how we’re counting James Buchanan as a former President. If you count one bobblehead you have to count them all.)

Dr. Scripto has no ideas or positions of his own. Instead, he has an entire team of writers who carefully script everything he has ever said.

Dr. Scripto is famous just for being famous. He’s never actually done much of anything.

Dr. Scripto – hmmm, you know something? Maybe he is qualified to be a US President after all!

In all fairness, we should also note that the one thing Dr. Scripto does have over all the other candidates is a willingness to face the difficult (and often controversial) issues. Let the other candidates bicker over the economy, foreign policy, abortion rights, and other trivial matters. While they’re busy avoiding the pressing issues of the day, Dr. Scripto tackles them head-on. Will Barack Obama tell you how to write a script that can return all the subfolders whose name starts with a specific string? It doesn’t look like it; Mr. Obama seems uncharacteristically silent when it comes to this matter. But not Dr. Scripto:

strComputer = "."

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

Set colFolders = objWMIService.ExecQuery _
    ("Select * from Win32_Directory Where FileName LIKE 'script%'")

For Each objFolder in colFolders
    Wscript.Echo objFolder.Name

To begin with, we need to note that this script comes with one very important caveat: it needs to be run on Windows XP or later; it’s not going to work on Windows 2000. Why not? Because we used the LIKE operator in our WMI query, an operator that enables us to do a wildcard-type search. We can’t run this script on Windows 2000 for one simple reason: Windows 2000 doesn’t support the LIKE operator.

So does that mean you’re totally out of luck on Windows 2000? Well, not totally. As an alternative to using the LIKE operator you could simply return a collection of all the folders on a computer, then individually check each one to see if the string value script appears at the start of the name (i.e., the first six characters). That’s what this script does:

strComputer = "."

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

Set colFolders = objWMIService.ExecQuery _
    ("Select * from Win32_Directory")

For Each objFolder in colFolders
    If Left(objFolder.FileName, 6) = "script" Then
        Wscript.Echo objFolder.Name
    End If

Will that work? Yes. Will that, depending on the number of folders on your machine, have the potential to be painfully slow and to eat up all your system resources? Yes.

That’s why we recommend using the LIKE operator (unless you have no choice): our original script runs much faster and with much less wear-and-tear on your system resources. Best of all, it’s a fairly simple little script to boot. As you can see, we start out by doing nothing more complicated than connecting to the WMI service on the local computer.

Note. Yes, you can run this against a remote computer; simply assign the name of that remote computer to the variable strComputer, like so:

strComputer = "atl-fs-001"

After connecting to the WMI service, we then use this line of code to retrieve a collection of all the folders that start with the characters script:

Set colFolders = objWMIService.ExecQuery _
    ("Select * from Win32_Directory Where FileName LIKE 'script%'")

Again, this isn’t very complicated; we’re simply asking to get back all instances of the Win32_Directory class where the value of the FileName (folder name) property is “like” scripts%. This is simply the way you do a wildcard query in WMI: you use the LIKE operator, and you use a percent sign as the wildcard character. Suppose you were using the DIR command from the command prompt, and you wanted to see a list of files that started with the letters script. In that case, you’d use this command:

dir script*

In WMI, you do the same sort of thing, only you use the percent sign instead of the asterisk.

Note. Good question: yes, you can find folder names that end with the characters script; to do that, use this syntax: Where FileName LIKE ‘%script’. To find folder names that contain the characters script use this syntax: Where FileName LIKE ‘%script%’.

After issuing our query we next set up a For Each loop to loop through all the folders in the returned collection:

For Each objFolder in colFolders

Inside that loop we echo back the value of the folder Name (more commonly referred to as the folder path):

Wscript.Echo objFolder.Name

That’s going to give us output similar to this:

c:\program files\gpmc\scripts
c:\program files\log parser 2.2\samples\scripts
c:\program files\microsoft platform sdk\samples\sysmgmt\msi\scripts
c:\program files\powershell community extensions\scripts
c:\program files\specopssoft\specops command\admin tools\scripts

In other words, all the folders whose name (not path, but actual folder name) starts with script.

As currently configured, our script is going to search the entire hard disk for folders whose name starts with the string script. That might be more information than you need, and it might cause the script to run more slowly than you would like. But that’s OK; we can speed things up a bit by beefing up our WMI query. For example, suppose we’re only interested in folders found on drive C. In that case, we can add a second clause to our query, one that limits returned data to folders with a Drive property equal to C:

Set colFolders = objWMIService.ExecQuery _
    ("Select * from Win32_Directory Where FileName LIKE 'script%' AND Drive = 'C:' ")

Alternatively, maybe you want folders that are on drive C and are subfolders of the Documents and Settings folder. Okey-doke. To do that we just add a third Where clause, one that further restricts the returned data to folders where the Path (equal to the regular file path minus the drive letter) equals \\documents and settings\\:

Set colFolders = objWMIService.ExecQuery _
    ("Select * from Win32_Directory Where FileName LIKE 'script%' AND Drive = 'C:' " _
        & "AND Path LIKE '\\documents and settings\\%'")

Note. Yes, \\documents and settings\\ does look kind of weird, doesn’t it? However, because the \ is a reserved character in WMI, it must be ‘escaped” (prefaced with another \) any time we use it in a WQL query. Thus a path like \documents and settings\ gets turned into this: \\documents and settings\\.

And there you have it.

That’s all we have time for today, MD; right now we need to sit down with Dr. Scripto and discuss the possibility of him tossing his hat into the Presidential ring. Like we said, though, the Scripting Guys remain skeptical. It’s true that we got a Scripting Games email that raised the issue; however, just because a Scripting Games competitor sent us something doesn’t mean we have to pay attention to it. For example, when the Scripting Guy who writes this column was testing the Blackjack games for Event 10, he won a game, and was rewarded with the following message:

You are a wiener!

OK. On second thought, maybe Scripting Games competitors have more insight than we gave them credit for.


Comments are closed. Login to edit/delete your existing comments