Search code examples
loopsbatch-filepid

Batch: check for the PID each second


I need to check which is the PID of, for example, "notebook.exe" if this process is running in the tasklist, so I need to check this each second:

If I running this while the program is running, works:

echo off
cls
SETLOCAL EnableExtensions
SETLOCAL EnableDelayedExpansion


    for /f "TOKENS=1" %%a in ('wmic PROCESS where "Name='notebook.exe'" get ProcessID ^| findstr [0-9]') do set MyPID=%%a   
        @echo %USERNAME%-%COMPUTERNAME%-%MyPID%

But I need check this each second. The same but into a Loop, but doesn't work (MyPID variable is empty)

echo off
cls
SETLOCAL EnableExtensions
SETLOCAL EnableDelayedExpansion

for /L %%n in (1,0,10) do (
    for /f "TOKENS=1" %%a in ('wmic PROCESS where "Name='notebook.exe'" get ProcessID ^| findstr [0-9]') do set MyPID=%%a   
        @echo %USERNAME%-%COMPUTERNAME%-%MyPID%
)

Is it possible?


Solution

  • You are trying to use a variable that you have set inside a for loop. Since batch is executed line by line and code blocks (such as loops) are counted as one line, this will not work because batch will first expand %MyPID% to whatever it value was, and then execute the entire for loop.

    You came close to the way to fix this. Using Enable DelayedExpansion is part of the trick. but you also need to use ! around variables inside the loop to mark them as delayed.

    So in conclusion, this should work:

    @echo off
    cls
    SETLOCAL EnableExtensions
    SETLOCAL EnableDelayedExpansion
    
    for /L %%n in (1,0,10) do (
        for /f "TOKENS=1" %%a in ('wmic PROCESS where "Name='notebook.exe'" get ProcessID ^| findstr [0-9]') do set MyPID=%%a   
            echo %USERNAME%-%COMPUTERNAME%-!MyPID!
    )
    

    However, note that loops in batch are made much easier using labels, so this would work too, removing the need for the delayed expansion:

    @echo off
    cls
    SETLOCAL EnableExtensions
    
    :loop
    
    for /f "TOKENS=1" %%a in ('wmic PROCESS where "Name='notebook.exe'" get ProcessID ^| findstr [0-9]') do set MyPID=%%a   
    echo %USERNAME%-%COMPUTERNAME%-%MyPID%
    timeout /t 1 /nobreak >nul
    
    goto :loop
    

    the timeout /t 1 also makes sure it waits 1 second before going back to :loop