qwerty12345
qwerty12345

Reputation: 87

Batch to kill a process either by PID or process name, depending on user input

I want to create a batch file to kill a process either by id or by name depending on the user's choice. For example if he chooses 1, then he is promoted to enter the pid and then the code executes the command taskkill /PID processNumber /F, if he selects 2, he enters the process name and the code executes taskkill /IM processName.exe /F

My issue is that the code always enters a loop after entering either the pid or name.

Here's my code:

@echo off
title TASKKILL
tasklist
echo _____________________________________________________________
echo Press 1 to choose PID
echo Press 2 to choose Process Name
set /p option=
if %option% == 1 goto id
if %option% == 2 goto proc
goto out
:id
set /p pid="Enter the PID of the process you want to kill: "
echo %pid%
taskkill /PID %pid% /F
:proc
set /p processName="Enter the name of the process you want to kill: "
echo %processName%
taskkill /IM %processName%.exe /F
pause

Upvotes: 1

Views: 704

Answers (1)

Tyl
Tyl

Reputation: 5252

Try this:

@echo off
title TASKKILL
tasklist
echo _____________________________________________________________
echo Press 1 to choose PID
echo Press 2 to choose Process Name
set /p option=
if "%option%"=="1" goto :id
if "%option%"=="2" goto :proc

goto :out
:id
set /p pid="Enter the PID of the process you want to kill: "
echo %pid%
taskkill /PID %pid% /F

goto :out
:proc
set /p processName="Enter the name of the process you want to kill: "
echo %processName%
taskkill /IM %processName%.exe /F

:out
pause

You need to avoid the functions in the normal flow, by putting goto :eof or goto :outbranch before them.

So my change here was to add the :out label, and add goto :out before those two functions.

Note when using if to check variable's value, it's better to quote both the variable and the value you are checking, and leave no spaces before and after ==, like this:

if "%var%"=="value" echo "It's euqal!"

So I changed the if %option% == 1 part :)

Upvotes: 3

Related Questions