1

I get "taskkill was not expected" when I run the following code. The program closes before I can set the value of %stop%. How can i fix this error?

@echo off
set ucs=ucs.exe
cls
echo.
echo Check %ucs%...
tasklist /FI "IMAGENAME eq %ucs%" 2>NUL | find /I /N "%ucs%">NUL
if %errorlevel%==0 (
echo %ucs% is running!
echo You need to stop it before editing ucsdb
echo  1 - Stop
echo  0 - Menu
set /p "stop=Stop %ucs%?"
if %stop%==1 taskkill /im %ucs% /t && goto sqlitebrowser
if %stop%==0 goto sqlitemenu
if not %stop%==1 if not %stop%==2 echo Option "%stop%" not exist! &&   timeout /t 2 /nobreak >NUL && goto sqlitemenu
) ELSE (
echo %ucs% is not running
echo Loading SqliteBrowser...
timeout /t 2 /nobreak >nul
goto sqlitebrowser )

Code Edit:

setlocal EnableDelayedExpansion
cls
echo.
echo Check %ucs%...
pause
tasklist /FI "IMAGENAME eq %ucs%" 2>NUL | find /I /N "%ucs%">NUL
if %errorlevel%==0 (
echo %ucs% is running!
echo You need to stop it before editing ucsdb
echo  1 - Stop
echo  0 - Menu
set /p "stop=Stop %ucs%?"
if !stop!==1 taskkill /im %ucs% /t && goto sqlitebrowser
if !stop!==0 goto sqlitemenu
if not !stop!==1 if not !stop!==0 echo Options "!stop!" not exist! && timeout /t 2 /nobreak >nul && goto sqlitemenu
...

if not !stop!==1 if not !stop!==0 echo Options "!stop!" not exist! Not work properly

Blank517
  • 23
  • 3
  • 1
    I'm pretty sure variable `%stop%` is not defined... – aschipfl Mar 31 '16 at 11:34
  • 2
    Possible duplicate of [Example of delayed expansion in batch file](http://stackoverflow.com/questions/10558316/example-of-delayed-expansion-in-batch-file) – Dennis van Gils Mar 31 '16 at 11:58
  • The program closes before I can set the value of %stop%. – Blank517 Mar 31 '16 at 12:36
  • to your edited code (last code line): you don't need any `if` here because you already handled `0` and `1`. Just `echo Opions...` is enough. (I assume `2` is a typo and should be `0`) – Stephan Mar 31 '16 at 14:38
  • Thanks now all works! – Blank517 Mar 31 '16 at 15:05
  • 1
    You might prefer to use the command `choice /c 10 /n /m "Stop %ucs%?"` instead of `set`. The `choice` command will only allow the user to enter 1 or 0, so you don't have to validate it yourself. – Klitos Kyriacou Mar 31 '16 at 15:24

1 Answers1

0

The problem is that you have an opening parenthesis here:

if %errorlevel%==0 (

This means that all commands up to the closing parenthesis are treated as if there were all on one line. Environment variables are immediately expanded. In particular, it tries to expand %stop%. However, you haven't defined it yet, so it expands to the empty string and your if statement looks like this:

if ==1 taskkill [etc...]

What you need to do is use delayed expansion. Read the link from Dennis van Gils' comment.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
Klitos Kyriacou
  • 10,634
  • 2
  • 38
  • 70