Search code examples
cmdpid

PID lookup to recall and kill task


I'd like to create the below two separate lines of cmd script into a bat file. The PID changes so I'm having a hard time figuring out how to set this service PID to be dynamic. Any help would be welcomed thank you!!

sc queryex DWDesktopService

taskkill /f /pid ####


Solution

  • You just need to scrape the PID value out of the sc output. It is awkward in cmd scripting. Change the service name to yours. When you are satisfied that the correct PID will be killed, remove the echo from the TASKKILL line.

    FOR /F "usebackq delims=: tokens=1,2" %%a IN (`sc queryex "BITS" ^| FIND /I " PID "`) DO (
        SET "PID=%%b"
    )
    echo TASKKILL /F /PID %PID%