batch-filecmdwmicwmi-query

Not equal operator not working with WMIC command in for loop of batch file


I wrote this batch to get the number of active processes given a certain command line value, but the not equal operator I use in the query to exclude WMIC.exe itself doesn't work, and the batch returns a counter incremented by 1 since it also includes the WMIC.exe process. Here the batch 'count-process-by-command-line.cmd':

if "%~1%" == "" (
    echo No command line expression in input
    goto end
)
>nul chcp 65001
set /a cycleCounter=0
FOR /F %%T IN ('Wmic process where^(name ^!^="WMIC.exe" and COMMANDLINE LIKE "%%%~1%%"^)get ProcessId^|more +1') DO (
    call set processId=%%T
    if "!processId!" neq "" (
        echo Process ID !processId!
        set /a cycleCounter+=1
    )
)
set %2=!cycleCounter!
:end

... And here the test code batch:

@echo off
setlocal enableDelayedExpansion
call count-process-by-command-line.cmd "test" TEST
echo !TEST!
endlocal

Solution

  • I'd advise that you use a slightly different method, (now tested):

    @Echo Off
    SetLocal EnableExtensions DisableDelayedExpansion
    
    Set "cycleCounter=-1"
    
    If "%~1" == "" (Echo No commandline expression in input.
        GoTo EndIt
    )
    
    Set /A cycleCounter += 1
    For /F "Tokens=5 Delims=<>" %%G In ('%SystemRoot%\System32\wbem\WMIC.exe Process
     Where "CommandLine Like '%%%~1%%' And Not CommandLine Like '%%WMIC.exe%%'"
     Get ProcessId /Format:MOF 2^>NUL'
    ) Do Set /A _=%%G 2>NUL && Set /A cycleCounter += 1
    
    :EndIt
    Exit /B %cycleCounter%
    
    @Echo Off
    SetLocal EnableExtensions DisableDelayedExpansion
    
    Call "%~dp0count-process-by-command-line.cmd" "test"
    Echo %ErrorLevel%
    Pause