答案关于批处理文件比较变量与常量失败 https://stackoverflow.com/a/42448601/3074564在第一章中解释了如何调试批处理文件not双击它,但通过打开命令提示符窗口并从此窗口中运行批处理文件来查看由语法错误引起的错误消息,从而导致退出批处理文件执行。
SET status="
这一行定义了环境变量status
与价值"
.
我想你想使用:
SET "status="
此行删除可能存在的环境变量status
,但是您通过省略第一个双引号来编码错误。
命令PING sets 错误级别 to 0
关于成功和1
出现诸如无法 ping 通目标之类的错误。
但由于某种未知的原因,您不想评估退出代码PING并解析输出PING by FIND并评估退出代码FIND.
的用法FIND在我看来,这里完全没有必要。
退出代码的评估FIND根据此退出代码已经足以继续,但是根据以下值将两个带空格的不同字符串分配给环境变量错误级别.
多一个IF用于或多或少取决于退出代码的分支PING.
这是由于语法错误导致退出批处理执行的错误。
IF %status%==%internet%(
在第一次比较的基础上扩展为
IF " == Connected to the internet. (
or to
IF " == Not connected to the internet. (
Windows 命令解释器无法正确处理这两行,由输出到控制台的语法错误消息指示,当从命令提示符窗口中执行批处理文件时可以读取该消息。
比较包含命令分隔符 SPACE 的字符串需要将两个字符串括在双引号中进行比较,即使用:
IF "%status%" == "%internet%" (
但由于环境变量的原因,即使这样也无济于事status
用单双引号定义,这会导致第一次比较时左字符串最终出现"""
这再次导致语法错误。
Note:双引号字符包含在字符串比较中。
下面的块也很有趣:
IF %status%==%internet%(
goto :start_test
) ELSE (
goto :teller
)
:teller
The ELSE分支用于跳转到在任何情况下都会执行的行ELSE分支根本不存在。所以完整的ELSE分支是完全没有必要的。
出于上述所有原因,我建议将批处理代码简化为:
@echo off
set "Status=2"
:ConnectionTest
%SystemRoot%\System32\ping.exe -n 2 -w 700 www.google.com >nul
if errorlevel 1 (
if not "%Status%" == "1" echo %TIME% Not connected to the internet.
set "Status=1"
) else (
if not "%Status%" == "0" echo %TIME% Connected to the internet.
set "Status=0"
)
%SystemRoot%\System32\timeout.exe /T 5 >nul
goto ConnectionTest
这里可以省略所有双引号并使用:
@echo off
set Status=2
:ConnectionTest
%SystemRoot%\System32\ping.exe -n 2 -w 700 www.google.com >nul
if errorlevel 1 (
if not %Status% == 1 echo %TIME% Not connected to the internet.
set Status=1
) else (
if not %Status% == 0 echo %TIME% Connected to the internet.
set Status=0
)
%SystemRoot%\System32\timeout.exe /T 5 >nul
goto ConnectionTest
为了了解所使用的命令及其工作原理,请打开命令提示符窗口,执行以下命令,并仔细阅读为每个命令显示的所有帮助页面。
echo /?
goto /?
if /?
ping /?
set /?
timeout /?
另请阅读 Microsoft 的文章:使用命令重定向运算符 https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-xp/bb490982(v=technet.10).