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

20,907

Solution 1

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!
 )

Solution 2

It's much easier to just do taskkill /f /fi "SERVICES eq <service_short_name>"

Solution 3

@echo off

for /f "tokens= delims=" %%# in ('
  wmic service where "name='Service'" get ProcessId /format:value
') do (
  for /f "tokens=* delims=" %%$ in ("%%#") do set "%%$"
)

taskkill /pid %ProcessId% /f
Share:
20,907
ilce
Author by

ilce

Updated on November 03, 2020

Comments

  • ilce
    ilce over 3 years

    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?

  • rojo
    rojo almost 9 years
    Beware that many services may share the same PID. Try for /f "tokens=3" %A in ('sc queryex w32time ^| find "PID"') do wmic service where "ProcessID=%A" get caption,name,processid /value from a cmd prompt.
  • Eryk Sun
    Eryk Sun almost 9 years
    The OP didn't ask for code to kill the service, Surely in that case you would just use sc.exe to stop it rather than directly kill the process, which could host multiple services. You could also use something like tasklist /svc /fi "services eq %serviceName%" /fo list to get the PID plus a list of all services hosted by the process.
  • Codename K
    Codename K over 6 years
    It seems that taskkill /F /PID !pid! should be taskkill /F /PID %pid%
  • Neilski
    Neilski over 3 years
    @CodenameK - I agree. I edited the answer but it appears that my edit was rejected.