Reputation: 23
i try to write a tiny batch file which shall react in different way dependent on a parameter. Unfortunately the "if" statement whch compares 2 strings seem not to work as expected. The code used is:
@echo off
if "%1"=="" goto Usage
echo "Parameter: %1"
IF /I "%1"=="START" {
echo "Why the hell is %1 == Start?"
SET Parameter=start
goto :execute
} else if /I "%1"=="STOP" {
SET Parameter=stop
goto :execute
}
echo "Parameter %1% invalid"
:Usage
echo "Synapsis:"
echo " SwitchServices Start|Stop"
goto :EOF
:execute
SET servicename=Dnscache
SET filename=Dnscache.exe
CALL :%parameter%_Service
goto :EOF
:stop_Service
echo ... stopping service ...
net stop %servicename%
if (ERRORLEVEL GTR 0) call :kill_Service
sc config %servicename% start= disabled
Service stopped.
exit /b
:kill_Service
taskkill /f /IM %filename%
exit /b
:start_Service
echo ... starting service ...
sc config %servicename% start= auto
net start %servicename%
exit /b
:EOF
The result is:
c:\Users\kollenba\Documents\Temp>KapschServices.cmd xxx
"Parameter: xxx"
"Why the hell is xxx == Start?"
... starting service ...
[SC] ChangeServiceConfig ERFOLG
Der angeforderte Dienst wurde bereits gestartet.
I do not understand why the condition
if /I "%1"=="START"
does not work as expected. Any hints?
Precondition: the batch file must be executed with administrator permissions to allow the "net start" command. Used OS: Windows 7
Upvotes: 2
Views: 2533
Reputation: 3122
In batch we don't use braces to enclose if statements, instead we use parenthesis. So replace this:
IF /I "%1"=="START" {
echo "Why the hell is %1 == Start?"
SET Parameter=start
goto :execute
} else if /I "%1"=="STOP" {
SET Parameter=stop
goto :execute
}
By this one:
IF /I "%1"=="START" (
echo "Why the hell is %1 == Start?"
SET Parameter=start
goto :execute
) else if /I "%1"=="STOP" (
SET Parameter=stop
goto :execute
)
You are also missing an echo
before Service stopped.
And a bonus tip: You actually don't need the :EOF
label because goto :EOF
will always take you to the End Of File
Upvotes: 2