What could PID be useful for? It is unique number in the current moment.
-- With PID it is easy to refer to own process. The TASKLIST utility is not robust - just launch two instances of cmd.exe and you can't say which one is your own.
-- It can be very useful when creating temporary files or directories. The %RANDOM% variable as the part of the filename can lead to conflicts in pipes.
In this post I am offering tiny script cmdpid.bat which helps to detect PID of the current cmd.exe instance. The found value is stored to %CMDPID% variable. Functionality is implemented by powershell. The essence of the solution is expressed in 4 lines of the script after the :cmdpid label that can be copied-and-pasted in your scripts. The rest of the script is wrapper for convenient usage as a standalone tool.
Code: Select all
@echo off
if "%~1" == "/?" goto :help
if "%~1" == "-?" goto :help
if /i "%~1" == "/h" goto :help
if /i "%~1" == "-h" goto :help
for %%p in ( powershell.exe ) do if "%%~$PATH:p" == "" (
>&2 echo:%%p required.
exit /b 1
)
:cmdpid
for /f "tokens=*" %%p in ( '
set "PPID=(Get-WmiObject Win32_Process -Filter ProcessId=$P).ParentProcessId" ^& ^
call powershell -NoLogo -NoProfile -Command "$P = $pid; $P = %%PPID%%; %%PPID%%"
' ) do set CMDPID=%%p
goto :EOF
:help
echo:Calculates the Process ID of the Command Prompt
echo:and assigns it to the CMDPID variable.
echo:
echo:Usage: %~n0