Windows批量字符串比较if语句错误?

标签 windows batch-file if-statement string-comparison

我尝试编写一个小批处理文件,该文件将根据参数以不同的方式使用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/

相关文章:

c++ - 如何在 Mingw Gcc 中声明和链接到 RoInitialize、RoUninitialize、RoGetActivationFactory 和 HSTRING 函数

c - 从 COM 端口读取会破坏线路

c++ - GetProcAddress 函数返回 NULL

internet-explorer - 如何从批处理文件打开和关闭 Internet Explorer?

ios - if 语句不返回任何内容

python - if 语句每次都采用相同的路径;可能的 str v. int 冲突

windows - BASH:从字符串中去除换行符(读取行)

batch-file - cmd.exe 相当于/dev/stdout,写入标准输出 'as a file'

windows - & 和 | 是做什么的运算符(operator)在批处理文件中做什么?

java - Android:子字符串和 IF