我尝试编写一个小批处理文件,该文件将根据参数以不同的方式使用react。 不幸的是,比较 2 个字符串的“if”语句似乎没有按预期工作。 使用的代码是:
@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
结果是:
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.
我不明白为什么会出现这种情况
if /I "%1"=="START"
未按预期工作。 有什么提示吗?
前提条件:批处理文件必须以管理员权限执行才能允许“net start”命令。 使用的操作系统:Windows 7
最佳答案
在批处理中,我们不使用大括号将 if 语句括起来,而是使用圆括号。所以替换这个:
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
}
通过这个:
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
)
在服务停止之前,您还缺少
回声
。
还有一个额外的提示:您实际上不需要 :EOF
标签,因为 goto :EOF
总是会将您带到文件末尾
关于Windows批量字符串比较if语句错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29081981/