Search code examples
windowsbatch-filevariablestaskkill

cmd taskkill work with hardcoded PID value but not with same value as variable


I am facing a strange situation inside a Windows batch script that I currently work on.

In this section I extract the PID of a parent process, using its child's name (%PROCESS_NAME%). It work well and I can echo PARENT_PID without problems :

for /f "usebackq tokens=2 delims==" %%a in (`wmic process where ^(name^='%PROCESS_NAME%'^) get parentprocessid /value`) do (
        set PARENT_PID=%%a
    )

echo !PARENT_PID!

Result show the expected value :

16392


The problem is in next line :

taskkill /f /t /pid !PARENT_PID!

The process doesn't get killed and the script showing a strange text (I am working in a french environment) :

" est introuvable.sus "16392


If I replace !PARENT_PID! with the hardcoded PID value like this :

taskkill /f /t /pid 16392

Everything works fine and the parent process and its child are killed.

I tried many thing but cannot figure out what is wrong. If anyone has an idea, I'm interested to kow, thanks !


Solution

  • Try like this and you'll see the problem:

    @echo off
    setlocal enableDelayedExpansion
    for /f "usebackq tokens=2 delims==" %%a in (`wmic process where "name='explorer.exe'" get parentprocessid /value`) do (
            set PARENT_PID=%%a
        )
    
    echo -!PARENT_PID!-
    

    WMIC output sets one additional carriage return at the end. Here you can find a workaround (with an additional for loop):

    @echo off
    setlocal enableDelayedExpansion
    for /f "usebackq tokens=2 delims==" %%a in (`wmic process where "name='explorer.exe'" get parentprocessid /value`) do (
            for /f "tokens=* delims=" %%# in ("%%~a") do set "PARENT_PID=%%#"
        )
    
    echo -!PARENT_PID!-