Sunday, January 5, 2014

How to Find the Process ID of this instance of CMD.EXE

Say you are writing a CMD.EXE script and would like to know the pid of the shell. Easy? No. CMD.EXE does not provide a $PID as Bash does so it takes a bit of contorting to get there (and you will mess up the window title):
@echo off

set r=%RANDOM%
for /f "usebackq tokens=2" %%a in (`" \
  tasklist /v /fi "imagename eq cmd.exe"| \
  %windir%\System32\find "SUPERSECRETTITLE %r%" \
  "`) do set PID=%%a

echo PID is %PID%
Note: Blogspot has a funny way to place text into columns. I broke the "for" command line into multiple lines using "\" -- you need to make it back a superlong command line for this to work.

Bonus (continuation): Find out if this CMD.exe was started with "/K" so you know to do "exit 0" or "exit /b 0":
wmic process where (name="cmd.exe" and processid=%PID%)\
  get commandline /value | \
  %windir%\system32\find " /K " >nul
The point of all this is that one does not need PowerShell to do useful Win32 scripting.