Search code examples
windowsbatch-filecmdwmic

Fastest way to get the PID of the current running terminal and save to a variable


I need to get the PID of each open terminal.

I have something in the works right now. However, it doesn't give the correct PID, and it's a little slow.

@echo off
rem Note: Session Name for privileged Administrative consoles is sometimes blank.
if not defined SESSIONNAME set SESSIONNAME=Console

setlocal
set instance=%DATE% %TIME% %RANDOM%
title %instance%

rem PID Find
for /f "usebackq tokens=2" %%a in (`tasklist /FO list /FI "SESSIONNAME eq %SESSIONNAME%" /FI "USERNAME eq %USERNAME%" /FI "WINDOWTITLE eq %instance%" ^| find /i "PID:"`) do set PID=%%a
if not defined PID for /f "usebackq tokens=2" %%a in (`tasklist /FO list /FI "SESSIONNAME eq %SESSIONNAME%" /FI "USERNAME eq %USERNAME%" /FI "WINDOWTITLE eq Administrator:  %instance%" ^| find /i "PID:"`) do set PID=%%a
if not defined PID echo !Error: Could not get PID of current process.  Exiting.& exit /b 1

echo Here's the PID: %PID%

I'm not sure how to explain it, but whenever this runs, it doesn't give the PID of the cmd.exe, but it returns the PID of the overall process itself. So if I ran the normal cmd, it will return the right PID, but if I ran a different terminal like Cmder, it will give the PID of the Cmder, not its affiliated cmd.exe.

I've seen a lot of solutions that use a for loop with wmic, but I can't seem to get it to work. Every time I try it, the PID it returns is always different each time I run it, which is obviously wrong.

I can use the following, and it works with 3rd party terminals AND is faster than what I have above:

wmic process where "name='WMIC.exe'" get parentprocessid

I'm just not sure how I can extract the PID out of the output of this. Is there any quicker way of getting the PID of a terminal?


Solution

  • Using the idea in my comment:

    WMIC /OUTPUT:temp.txt Process Where "Caption='WMIC.exe'" Get ParentProcessID
    For /F "Skip=1" %%A In ('Type temp.txt') Do If Not Defined PID Set "PID=%%A"
    Del temp.txt
    Echo=%PID%
    

    You can adjust your WMIC command, to use Where "CommandLine Like…if you feel that there's a possibility of another WMIC process running. That will probably add a small time increase though.