A2oz

How to Get Process ID in Windows Batch File

Published in Windows Batch Scripting 2 mins read

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

  1. Run the tasklist command: This command lists all running processes and their associated information, including the PID.
  2. Filter the output: Use the | findstr command to filter the output based on the process name or other criteria.
  3. 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 the for /f loop to iterate through the output of the tasklist | findstr "notepad.exe" command. The tokens=2 parameter specifies that the second token (separated by a colon) should be extracted, which is the PID. The delims: 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 like findstr, grep, or sed 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.

Related Articles