我在 Batch 中尝试使用 IF,但没有按预期工作

Im trying something with IF in Batch but is not working as im expecting

我需要做一个脚本来查找文件中的一些文本,并在 %userprofile% 路径中查找文件本身,它工作正常但是当我试图统一它而不是输出 2确认消息只输出 1,有些事情没有按预期进行,这是代码:

hostname > hstnm.txt
SET /p hstnm=<hstnm.txt
SET pccer=.filextension1
SET pcsip=.filextension2
SET fullhost=%hstnm%%pccer%
SET fullsip=%hstnm%%pcsip%
SET fullroute=%userprofile%\thepath\%fullhost%
SET siproute=%userprofile%\thepath\%fullsip%

FINDSTR /m "<Protocol>TLS</Protocol>" "%siproute%"
IF %errorlevel%==0 (
 SET siptest="true"
) ELSE (
 SET siptest="false"
)

IF EXIST "%fullroute%" (
 SET certest="true"
) ELSE (
 SET certest="false"
)

IF %siptest%=="true" & %certest%=="true" (
ECHO message if everything good
) ELSE (
ECHO message if something bad
)
pause

FINDSTR 和 IF EXIST 工作正常(如果您将 SET 换成 ECHO,它会显示一条消息)。问题出现在使用 %certest% 和 %siproute% 的部分,它什么都不做,只是输出这个(如果我退出 @echo off)

...
C:\path>IF EXIST "C:\Users\Administrador\Appdata\Roaming\Interactive Intelligence\PureCloud Softphone\certificates\sip\GSSES0401107C.grupogss.corp.cer" (SET certest="true" )  ELSE (SET certest="false" )
No se esperaba & en este momento.
C:\path>IF "true"=="true" & "true"=="true" (
C:\path>

请帮帮我!提前致谢。

有问题的行有一个“&”字符,我假设您正试图将其用作布尔 AND 运算符 - 'IF' 在 CMD 中没有 AND 运算符. CMD 命令链机制确实如此,这就是可能出现混淆的地方。我通常在这种情况下嵌套 IF:

IF %siptest%=="true" (  
    IF %certest%=="true" (...

'&'运算符 " 简单地将多个命令链接在一行中:

dir & cd \ & dir & del myfile.txt

全部上面的命令会一个接一个的执行

另一方面,“&&”运算符的工作方式有点像 AND 运算符,因为它仅在前一个命令的 ERRORLEVEL 为“0”(无错误)时才执行链中的下一个命令。

del myfile.txt && echo Done! && cd c:\

只有在del 命令returns 错误级别为0 时才会执行echo 命令。 cd 命令依赖于结果所有之前的命令,这意味着它只需要一个失败的命令就可以打破链条。

我个人也很小心我如何使用变量并且总是将它们括起来:

IF "%MYVAR%"=="0" (...

我这样做是因为最后你不是在比较一个变量,而是一个简单的字符串比较; CMD 变量在对它们进行任何操作之前被替换为它们所代表的内容。发生替换时可以进行一定程度的调整,但最终总是字符串比较。这意味着如果变量没有任何内容(它发生了)并且你使用它进行比较,没有某种封闭,那么你的脚本将失败并退出,因为生成的 IF 格式错误。

https://ss64.com/nt/if.html
https://ss64.com/nt/syntax-conditional.html

  1. 有时候我们不需要做括号if的。
  2. 已经有一个包含名为 %COMPUTERNAME% 的主机名的变量,您可以使用它而无需创建临时文件
  3. Pre-set 变量,并且仅在文件不存在时更改它们而不是 if else 语句。
  4. 嵌套 if 的不使用 &。我们只是将下一个放在另一个之后。 if 一个条件 returns 为真,它会执行下一个,依此类推 if 任何条件失败,它将停止处理该行的其余部分并继续下一行:
@echo off
set "pccer=.filextension1"
set "pcsip=.filextension2"
set "fullhost=%COMPUTERNAME%%pccer%"
set "fullsip=%COMPUTERNAME%%pcsip%"
set "fullroute=%userprofile%\thepath\%fullhost%"
set "siproute=%userprofile%\thepath\%fullsip%"
set "siptest=false"
set "certest=false"

FINDSTR /m "<Protocol>TLS</Protocol>" "%siproute%"
if not errorlevel 1 set "siptest=true"
if exist "%fullroute%" set "certest=true"

if "%siptest%" == "true" if "%certest%" == "true" echo message if everything good & goto :done
echo message if something bad

:done
pause