Search code examples
windowsbatch-filecmdwmictaskmanager

Is there any way to remove the entries with same process names?


I'm trying to get the top 10 memory consuming processes and I am using the code provided as an answer in this Question. It works fine except that I don't want multiple entries of processes consuming different memory size and I was unable to sort it because it's memory consumption is different. The code is:

@echo off
setlocal EnableDelayedExpansion

(for /F "skip=1 tokens=1,2" %%a in ('wmic process get name^,workingsetsize') do (
set "size=         %%b"
echo !size:~-10!:%%a
)) > wmicc.txt
set i=0
for /F "skip=1 delims=" %%a in ('sort /R wmicc.txt') do (
echo %%a
set /A i+=1
if !i! equ 25 goto :end
)
:end

Can I get the output as:

96931840:iexplore.exe
82161664:explorer.exe
42319872:svchost.exe
31469568:dwm.exe
25690112:SearchIndexer.exe
17002496:taskhostex.exe
11007590:VCExpress.exe
8033894:avp.exe
7190528 :Skype.exe
7000416 :SkypeBrowserHost.exe

Instead of the output from existing code:

96931840:iexplore.exe
82161664:explorer.exe
42319872:svchost.exe
33656832:svchost.exe
31469568:dwm.exe
26943488:iexplore.exe
25690112:SearchIndexer.exe
18550784:svchost.exe
17002496:taskhostex.exe
16343040:svchost.exe

Solution

  • @echo off
    setlocal EnableDelayedExpansion
    
    set num=25
    
    set /A skip=-num
    for /F "skip=1 tokens=1,2" %%a in ('wmic process get name^,workingsetsize') do (
       set "size=         %%b"
       set "size=!size:~-10!"
       if not defined proc[%%a] (
          set "proc[%%a]=!size!"
          set "size[!size!:%%a]=1"
          set /A skip+=1
       ) else if %%b gtr !proc[%%a]! (
          set "size[!proc[%%a]!:%%a]="
          set "proc[%%a]=!size!"
          set "size[!size!:%%a]=1"
       )
    )
    
    if %skip% lss 1 (set "skip=") else set "skip=skip=%skip%"
    for /F "%skip% tokens=2 delims=[]" %%a in ('set size[') do echo %%a
    

    Output example:

       5517312:NisSrv.exe
       5537792:HD-LogRotatorService.exe
       5939200:spoolsv.exe
       6062080:WUDFHost.exe
       6168576:igfxpers.exe
       6279168:conhost.exe
       6369280:wmpnetwk.exe
       6533120:hkcmd.exe
       6692864:igfxtray.exe
       8073216:notepad.exe
       8077312:WMIC.exe
       8105984:taskhost.exe
       9306112:lsass.exe
      11157504:winlogon.exe
      11767808:taskhostex.exe
      13402112:SkyDrive.exe
      16629760:TabTip.exe
      17121280:SearchIndexer.exe
      26120192:HD-Agent.exe
      32325632:csrss.exe
      36429824:svchost.exe
      43114496:dwm.exe
     101998592:explorer.exe
     110260224:MsMpEng.exe
     114425856:chrome.exe