Q:
Hi, scripting guy! I want to do something very simple: Call the Dir command in the script. But it does not seem to work. How can I implement my ideas?
-- Cr, Mexico City, Mexico
A:
Hello, Cr. From your email, you want to do a simple job similar to the following:
Set objshell = Createobject ("wscript. Shell") objshell. Run ("dir"), 1, true
However, you do not get a list of all files in the current folder, but get a messageThe system cannot find the file specified(The system cannot find the specified file ). Why?
The cause of this problem is as follows:NoA file called "dir. You can search dir.exe or dir.com; they cannot be found. In fact, DIR is an internal command of the command line shell (cmd.exe or command.exe, depending on the version of the running Windows. That is to say, the Dir command can only be used in the command line window. To prove this, open the command line window and enterDirAnd press Enter. You should see a list of all files and folders in the current directory. OpenRunDialog box, enterDirAnd press Enter. You will see an error message as follows:
However, this does not mean you are unlucky. ActuallyOrThere is a way to call the Dir command in the script; but you must be smart enough. Because DIR is an internal command, you can only call command line surgery and pass dir to it as a command line parameter. Let's take a look at a script that uses this technique, and then 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 then uses the run method to call the Dir command in the second line. However, please note: we do not directly specify dir; but instead specify% Comspec %/K dir. The command string can be decomposed into the following:
% comspec % |
open a command line window. % Comspec % is an environment variable pointing to the shell of the current command line. By using % comspec %, you do not have to worry about whether the command line shell is cmd.exe or command.exe; % comspec % will automatically select the correct one. |
/k |
after calling the Dir command, ensure that the window is always open. This is the use of the/k parameter. If we want to ensure that the command window will be automatically closed after the Dir command is called, we should change/K (keep) to/C (close ). |
dir |
run the Dir command. |