简体   繁体   中英

Kill a java process in windows programmatically

I have many executable jar files which I am running in a windows server. Sometime, I need to redeploy some of the applications. For that, I need to first stop the existing process and then start the new process. In linux environment I am using pkill to kill the process based on the jar file name. But in windows, all the java processes will be named as "java.exe" only. I need to write a batch file to do this start and stop operations. How can I kill the jar file based on the name.

Assume that my jar file is named as common-api.jar . Running the command jps -ml | find "common" jps -ml | find "common" would give the result as

6968 common-api.jar

I can kill the process by taskkill /f /PID 6968

But How can I extract the process id from the first command and pass it to the taskkill command ?

for /f "delims= " %%a in ('jps -ml ^| find /i "common"') do set PID=%%a
taskkill /f /PID %PID%

or from command prompt:

for /f "delims= " %a in ('jps -ml ^| find /i "common"') do set PID=%a

In vbscript we can do something like that just give a try with it :

Option Explicit
Call KillProcessbyName("common-api.jar")
'**********************************************************************************************
Sub KillProcessbyName(FileName)
    On Error Resume Next
    Dim WshShell,strComputer,objWMIService,colProcesses,objProcess
    Set WshShell = CreateObject("Wscript.Shell")
    strComputer = "."
    Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
    Set colProcesses = objWMIService.ExecQuery("SELECT * FROM Win32_Process")
    For Each objProcess in colProcesses
        If InStr(objProcess.CommandLine,FileName) > 0 Then
            If Err <> 0 Then
                MsgBox Err.Description,VbCritical,Err.Description
            Else
                objProcess.Terminate(0) 
            End if
        End If
    Next
End Sub
'**********************************************************************************************

只要这样做:

for /f "tokens=1" %%A in ('jps -ml ^| find "common"') do (taskkill /F /PID %%A )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM