You can get the process ID (PID) of a running process in a Windows batch file using the tasklist
command and parsing the output. Here's how:
Using the tasklist
Command
- Run the
tasklist
command: This command lists all running processes and their associated information, including the PID. - Filter the output: Use the
| findstr
command to filter the output based on the process name or other criteria. - Extract the PID: Use the
for /f
loop to extract the PID from the filtered output.
Here's an example of getting the PID of a process named "notepad.exe":
@echo off
for /f "tokens=2 delims: " %%a in ('tasklist | findstr "notepad.exe"') do set PID=%%a
echo The PID of notepad.exe is: %PID%
pause
Explanation:
@echo off
: This line suppresses the echoing of commands in the batch file.for /f "tokens=2 delims: " %%a in ('tasklist | findstr "notepad.exe"') do set PID=%%a
: This line uses thefor /f
loop to iterate through the output of thetasklist | findstr "notepad.exe"
command. Thetokens=2
parameter specifies that the second token (separated by a colon) should be extracted, which is the PID. Thedelims:
parameter specifies that the colon character is used as the delimiter between tokens.echo The PID of notepad.exe is: %PID%
: This line prints the PID of the process to the console.pause
: This line pauses the execution of the batch file, allowing you to view the output.
Practical Insights
- You can use the
tasklist
command with various options to refine the output. For example, you can use the/FI
option to filter by process name, image path, or other criteria. - You can combine the
tasklist
command with other commands likefindstr
,grep
, orsed
to extract specific information from the output.
Remember: The PID of a process can change over time, so it's important to run the batch file each time you need to get the current PID.