Search code examples
windowsbatch-filecmdprocesspid

Find out how many parent processes a batch-file is running under


I've got a batch-file that is calling itself in multiple CMD sessions, for example:

@echo off
if "%var%"=="set" goto :begin
set var=set
call cmd /c %0

:begin
echo Inside CMD session! Executed under x processes
pause

What I'm trying to accomplish is to get the number of processes a batch-file is being called from.

Normal batch file:

| Batch-file
   | Batch script

Would return 1, as the batch-file is being called from the root process

Multiple process batch-file:

| Batch-file
   | CMD
      | Batch-file
         | Batch script

Would return 2, as the batch-file is being called from another batch-file.

A possible solution would be to get the root process identifier number (PID), and then analyse the wait chain for that process, which I'm able to accomplish easily in Task Manager:

Wait chain, Task Manager

Summary: How can I return the number of processes a batch-file is being executed under, with or without any third-party utilities?


Solution

  • @echo off
    setlocal
    
    if "%var%"=="3" goto :begin
    set /A var+=1
    cmd /C "%~F0"
    goto :EOF
    
    :begin
    echo Inside CMD session!
    
    wmic process where "name='cmd.exe'" get ExecutablePath,ParentProcessId,ProcessId > wmic.txt
    for /F "skip=1 tokens=1-3" %%a in ('type wmic.txt') do (
       ECHO %%a - Parent: %%b - PID: %%c
       set "Parent[%%c]=%%b"
       set "This=%%c"
    )
    
    set X=0
    :nextParent
       set /A X+=1
       call set "This=%%Parent[%This%]%%"
    if defined Parent[%This%] goto nextParent
    echo Executed under %X% processes
    

    Output example:

    Inside CMD session!
    C:\Windows\system32\cmd.exe - Parent: 3792 - PID: 4416
    C:\Windows\system32\cmd.exe - Parent: 4416 - PID: 3220
    C:\Windows\system32\cmd.exe - Parent: 3220 - PID: 1728
    C:\Windows\system32\cmd.exe - Parent: 1728 - PID: 3560
    Executed under 4 processes