找出一个batch file运行的父进程的数量

我有一个在多个CMD会话中调用自己的batch file,例如:

 @echo off if "%var%"=="set" goto :begin set var=set call cmd /c %0 :begin echo Inside CMD session! Executed under x processes pause 

我想要完成的是获取batch file被调用的进程数量。

正常batch file:

 | Batch-file | Batch script 

将返回1 ,因为从根进程调用batch file

多进程batch file:

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

会返回2 ,因为从另一个batch file调用batch file。

一个可能的解决scheme是获取根进程标识符号(PID),然后分析该进程的等待链,我可以在任务pipe理器中轻松完成:

等待链,任务管理器

简介: 如何在有或没有任何第三方实用程序的情况下返回batch file正在执行的进程数?

 @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 

输出示例:

 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 

我涉足了Aacini的代码,让树更加可视化

 Inside CMD session C:\WINDOWS\system32\cmd.exe - 1004:12424 C:\WINDOWS\system32\cmd.exe - 12424:12016 C:\WINDOWS\system32\cmd.exe - 12016:10592 C:\WINDOWS\system32\cmd.exe - 10592:11392 C:\WINDOWS\system32\cmd.exe - 11392:5616 Executed under 5 processes 

改变了中间部分

 Set "Space=" wmic process get ExecutablePath,ParentProcessId,ProcessId > wmic.txt for /F "tokens=1-3" %%a in ('type wmic.txt') do ( if /I "%%a" equ "%ComSpec%" ( Call ECHO %%a - %%Space%%%%b:%%c CAll Set "Space=%%Space%% " set "Parent[%%c]=%%b" set "This=%%c" ) )