Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check and correct user input when he omit the extension .exe to kill the process?

Tags:

batch-file

cmd

I have this batch to kill some process typed of course by the user and it works 5/5 when the user for example typed Calc.exe with the extension, but my issue now is to improve this batch in order to add automatically with this program if the user has omitted to add extension .exe like Calc without extension .exe will not work.

@Echo off & cls
Mode con cols=72 lines=7
Set TmpFile=TmpFile.txt
Set Resultat=KillResult.txt
If Exist %TmpFile% Del %TmpFile%
If Exist %Resultat% Del %Resultat%
::********************************************************************************************
:Main
Title Process Killer by Hackoo 2015
cls & color 0B
echo.
echo                Quel(s) processus voulez-vous fermer ?
echo.
set/p "process=Entrer le(s) nom(s) de(s) processus> "
cls & color 0C
Title Killing "%process%" ...
echo.
echo                       Killing "%process%" ...
echo.
echo %date% *** %time% >> %TmpFile%
For %%a in (%process%) Do Call :KillProcess %%a
Cmd /U /C Type %TmpFile% > %Resultat%
Start %Resultat%
echo.
Goto :Main
::*********************************************************************************************
:KillProcess
Taskkill /IM "%~1" /F >> %TmpFile% 2>&1
echo ***************************************************************************** >> %TmpFile% 
::*********************************************************************************************

So i'm focusing on this piece of code but no success ! this my little try :

:KillProcess
Set str=%~1
set str=%str:~-4%
echo.%str%
pause
if %str%==".exe" (Taskkill /IM "%~1" /F >> %TmpFile% 2>&1) || (Taskkill /IM "%~1.exe" /F >> %TmpFile% 2>&1)

So how to do that in batch ?

Thank you !

like image 442
Hackoo Avatar asked Mar 16 '23 18:03

Hackoo


1 Answers

If your files have never any other extension than .exe, you can use "%~n1.exe" to get the filename with .exe.

%~n1 is just the filename without extension. Than add .exe, and put quotes around it in case the filename contains a space.

But this will fail if your executable is example.program.exe, and the user entered example.program. In this case the result of "%~n1.exe" will be "example.exe". To avoid that, you have to check if the extension is .exe. You can use %~x1 to get just the extension.

See also Command Line arguments (Parameters) for more information.

like image 91
wimh Avatar answered Apr 06 '23 06:04

wimh