How Can I Call the Dir Command?
Hey, Scripting Guy! I’m trying to do something that seems pretty simple: call the dir command from a script. It doesn’t seem to work, though. How come?
— CR, Mexico City, Mexico
Hey, CR. It appears from your mail that you’re trying to do a simple thing like this:
Set objShell = CreateObject("Wscript.Shell") objShell.Run("dir"), 1, TRUE
However, instead of getting a list of everything in the current folder, you’re getting the message The system cannot find the file specified. What gives?
Well, what gives is this: there really isn’t a file named dir on your computer. Search for dir.exe or dir.com; you won’t find it. Instead, dir is actually a command built into the command shell (cmd.exe or command.exe, depending on the version of Windows you are running). That means dir is available only when you are running the command shell. To demonstrate this, open up a command window, type dir, and press ENTER. You should get a listing of all the files and folders in the current directory. Now, bring up the Run dialog box, type dir, and press ENTER. You should get an error message like this:
But that doesn’t mean you’re out of luck. As it turns out there actually is a way to call the dir command from within a script; you just have to be clever about it. Because dir is a command built into the command shell, what you do is call the command shell and pass dir as a command-line argument. Let’s take a look at a script that does the trick, then we’ll explain how it works:
Set objShell = CreateObject("Wscript.Shell") objShell.Run("%comspec% /k dir"), 1, TRUE
The first line of the script simply creates an instance of the WSH Shell object, and the second line uses the Run method to actually call the dir command. But note that we don’t specify dir directly; instead we specify %comspec% /k dir. This command string is broken down like this:
Opens up a command window. %comspec% is an environment variable that points to the current command shell. By using %comspec% you don’t have to worry about whether the command shell is cmd.exe or command.exe; %comspec% will pick the correct one.
Ensures that the window stays open after the dir command is called. That’s what the /k is for. If we wanted to make sure that the command window automatically closes after the dir command is called then we would change the /k (keep) to a /c (close).
Runs the dir command.