Get the PID of a Windows service by the name of the service

ilce picture ilce · Jun 19, 2015 · Viewed 17.3k times · Source

Is there a way of getting the PID of a windows service with a command in a batch script by just knowing the name of the service?

Answer

Filip Shulevski picture Filip Shulevski · Jun 19, 2015

Try the following code:

FOR /F "tokens=3" %%A IN ('sc queryex %serviceName% ^| findstr PID') DO (SET pid=%%A)
 IF "!pid!" NEQ "0" (
  taskkill /F /PID !pid!
 )