How to get own process pid from the command prompt in Windows
Solution 1:
Since none of the other solutions are bulletproof and built in, I figured I'd offer the following solution, but note that you'll need to parse/save the results somehow:
title mycmd
tasklist /v /fo csv | findstr /i "mycmd"
Solution 2:
Using PowerShell + WMI :
powershell (Get-WmiObject Win32_Process -Filter ProcessId=$PID).ParentProcessId
Using WMIC :
for /f %a in ('wmic os get LocalDateTime ^| findstr [0-9]') do set NOW=%a
wmic process where "Name='wmic.exe' and CreationDate > '%NOW%'" get ParentProcessId | findstr [0-9]
(as always, double the %
sign with for
in batch files)
Solution 3:
Expanding upon Tony Roth's answer:
title uniqueTitle
for /f "tokens=2 USEBACKQ" %f IN (`tasklist /NH /FI "WINDOWTITLE eq uniqueTitle*"`) Do echo %f
Using the WINDOWTITLE filter avoids the pipe so you can put it in a for loop and assign it to a variable with SET if you like:
title uniqueTitle
for /f "tokens=2 USEBACKQ" %f IN (`tasklist /NH /FI "WINDOWTITLE eq uniqueTitle*"`) Do set ourPID=%f
Removing the /v
makes it quicker, and the /NH
gets rid of the header line. You need the wildcard after "uniqueTitle"
because the window title actually contains the current command (thus it would go on and on if you tried to match it fully).