Kill windows process only if it is running – using tasklist, taskkill together – DOS Command

During maintenance activities at times we need to kill a process/task only if it is running. it is a little complex to identify when the process/task is running. Following simple script helps to do so in command prompt or batch file.

Change notepad.exe to different task you want to kill. you may filter based on task owner.

FOR /F "usebackq tokens=2" %i IN (`TASKLIST /NH /FI "ImageName eq notepad.exe"`) DO (if not %i == No taskkill /PID %i)

C:\Users\Vijred\Desktop>FOR /F "usebackq tokens=2" %i IN (`TASKLIST /NH /FI "ImageName eq notepad.exe"`) DO (if not %i == No taskkill /PID %i)

C:\Users\Vijred\Desktop>(if not 6240 == INFO: taskkill /PID 6240 )
SUCCESS: Sent termination signal to the process with PID 6240.

C:\Users\NareshG\Desktop>

If you are looking to kill first process alone, use following code, reference from http://stackoverflow.com/questions/9712399/pass-pids-from-tasklist-and-kill-processes-with-tasklist;

setlocal enabledelayedexpansion set flag=0 FOR /F "usebackq tokens=2" %%i IN (tasklist ^|findstr /r /b "notepad.exe") DO ( if !flag! == 0 ( echo !flag! taskkill /pid %%i set flag=1 echo !flag! ) ) endlocal

Kills a process only if running
Kill a task if it is running

– Vijred

Powershell way of doing the same work 🙂

Stop-Process -Name Notepad -ErrorAction SilentlyContinue
Advertisements
This entry was posted in commands, Productivity, Script, Windows Server and tagged , , , , . Bookmark the permalink.

One Response to Kill windows process only if it is running – using tasklist, taskkill together – DOS Command

  1. Pingback: Frequently used Windows Operating System commands | Blog for reference – Vijred

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s