-1

So, I'm trying to make my life a little easier by creating a batch file that will kill a particular process when I use a special command. Here is how it goes:

SET NAME = %1
IF NOT DEFINED NAME SET NAME = "firefox*"
SET fullcommandarg = "IMAGENAME eq " and NAME
TASKKILL /FI %fullcommandarg% /F

But I get an error that FI needs an argument. I'm not trying to learn how batch files work but I would like to know what I'm doing wrong here and also what the possible solution would be. Since Firefox is usually the application I close using this command I set it as default. How can I get this to work? Thanks in advance. P.S: Only comment here if you actually want to help. If you're going to tell me to go read a book or something snarky like that, I'll repeat that I'm not trying to learn more about batch files than is necessary for me. To those who actually want to help, reference links are welcome in case the explanation is too long or if you don't have the time to type it down or something.

Black Wind
  • 313
  • 1
  • 8
  • Batch is sensitive to spaces in a `SET` statement. `SET FLAG = N` sets a variable named "FLAG`Space`" to a value of "`Space`N". Use the syntax `set "name=string"` for best results - don't include quotes in the value assigned - it causes problems. The syntax for concatenating strings is `set "longstring=fixed text %shortstring%"` , not `and`. Since you are executing `taskkill` with `%fullcommandarg%` but setting fullcommandarg`space`, batch substitutes *NOTHING* for `%fullcommandarg%` – Magoo Oct 25 '20 at 08:36
  • @Magoo - thanks for that. I edited my file as you directed and now it works. :D – Black Wind Oct 25 '20 at 09:48

1 Answers1

0

To set a variable value inside an if-else you'll need to use setlocal EnableDelayedExpansion together with !NAME!. Also and isn't a command, as far as I know, to chain strings. Remember that SET sets variables values as strings ("..." isn't needed).

setlocal EnableDelayedExpansion
SETLOCAL EnableExtensions
SET NAME=%1
IF NOT DEFINED NAME SET NAME=firefox*
SET fullcommandarg=IMAGENAME eq !NAME!
TASKKILL /FI !fullcommandarg! /F
DadiBit
  • 769
  • 10
  • 22
  • The delayed-expansion-explanation is confusing, as you don't need it here. – Stephan Oct 25 '20 at 08:52
  • 1
    @DadiBit [Delayed expansion](https://ss64.com/nt/delayedexpansion.html) is not needed here as written already by Stephan. It is also not recommended to run __SETLOCAL__ twice to define the required execution environment. In this case `setlocal EnableExtensions DisableDelayedExpansion` (one command line) is recommended to define the execution environment which is the Windows default. Please read [this answer](https://stackoverflow.com/a/38676582/3074564) for details about the commands __SETLOCAL__ and __ENDLOCAL__ to get knowledge what happens on each execution of __SETLOCAL__ in background. – Mofi Oct 25 '20 at 10:36