Do you have a scripting-related question or problem? You can send your question or problem to firstname.lastname@example.org.
How can I obtain the process identifier (PID) of a program that a command-shell script executes so that the script can use that PID to manipulate the program?
You can use the Tlist (tlist.exe) utility to obtain PIDs on the fly. Tlist displays the name and PID of each active process. You can find Tlist under the \support\tools folder on the Windows 2000 CD-ROM or in the Microsoft Windows NT Server 4.0 Resource Kit.
After you have a program's PID, you can use it to manipulate the program. For example, suppose you start Notepad and you later want to terminate that process with the Kill (kill.exe) utility, another support tool on the Win2K CD-ROM. The script PID.bat in Listing 1 demonstrates how you can use Tlist to obtain Notepad's PID, then use that PID to terminate the Notepad process.
In PID.bat, the For /f command triggers the Tlist utility to execute. The command shell captures Tlist's output in memory, and the For /f command parses that output as if it were coming from a file. The command parses each line of output into its individual elements (i.e., the PID and the process name) and sets the %%i variable to the PID and the %%j variable to the process name. The For /f command then compares the value in %%j with the process name notepad.exe. If a match occurs, the For /f command sets the value of %%i to the %PID% variable. The script then uses the value in %PID% as input to the Kill utility, which terminates the Notepad process.
Let's take a closer look at the part of the For /f command that parses Tlist's output, which the code at callout A in Listing 1 shows. This part of the For /f command uses the usebackq option and encloses the Tlist command inside accent grave (`) characters (aka back quotes) and parentheses. The usebackq option and the use of accent grave characters are new to Win2K.
In NT and Windows 9x, you can typically use filenames that contain spaces in command-shell scripts, but you need to enclose the filenames in double quotes. However, an exception occurs with For /f commands. Inside a For /f command, you can't enclose a filename in double quotes because the command shell will interpret that filename as a literal string and try to parse it.
In Win2K, the usebackq option lets you use filenames with spaces inside a For /f command because the option prompts the command shell to use a slightly different syntax. When a For /f command specifies usebackq, the command shell interprets
- any text enclosed in double quotes (e.g., "text") as filenames
- any text enclosed in single quotes (e.g., 'text') as strings to parse
- any text enclosed in accent grave characters (e.g., `text`) as commands to execute
The usebackq option works only on Win2K machines. Because PID.bat uses this option, you can't run this script on NT or Win9x machines.