如果语句未按预期执行-批处理文件

时间:2019-05-16 01:57:42

标签: windows batch-file for-loop if-statement

我正在尝试在大量目前可以通过ConnectWise ScreenConnect访问的客户端计算机上安装RMM代理。我编写了一个批处理(cmd),以简化下载和安装过程,同时进行无提示安装。

但是,我遇到了让“ if”听“ for”字符串的问题。

我尝试在do之后更改符号,我尝试将==更改为EQU,然后将括号等的引号替换为无效。


:check
for /f "tokens=1-3" %%i in ('cmd bitsadmin /list ^| findstr syncroMSP') do (
    if "%%k"=="SUSPENDED" (
        echo Status is [%%k]
        goto success
    ) else (
        goto fail
    )
)

:success
explorer
echo If you had a suspended transfer, your script worked.
pause
exit /b

:fail
calc
your If you didn't have any suspended transfers, your script worked.
pause
exit /b

在没有任何传输作业处于活动状态的情况下,我希望看到“ else”命令正在运行,并最终看到计算器打开(对我来说,查看它工作的简单方法)。相反,我看到“状态为[%% k]”,然后打开浏览器。

编辑:今天早上运行了完全相同的批处理后,我得到了一个空的cmd窗口,上面有一个勾号的光标块...

1 个答案:

答案 0 :(得分:1)

如果bitsadmin /list | findstr syncroMSP不返回任何内容,则根本不会执行for循环,并且由于您的逻辑,下一个执行的代码是位于:success标签下的代码。

跳过else部分并稍微改变一下逻辑:

:check
for /f "tokens=1-3" %%i in ('bitsadmin /list ^| findstr syncroMSP') do (
    if "%%k"=="SUSPENDED" (
        echo Status is [%%k]
        goto success
    )
)

calc
your If you didn't have any suspended transfers, your script worked.
pause
exit /b

:success
explorer
echo If you had a suspended transfer, your script worked.
pause
exit /b

甚至更好的是,完全改变您的逻辑:

:check
set status=unknown
for /f "tokens=1-3" %%i in ('bitsadmin /list ^| findstr syncroMSP') do set "status=%%k"
echo Status is [%status%]
if "%status%" == "SUSPENDED" (
  explorer
  echo your script worked
  pause
  exit /b
)
calc
echo no suspended transfer
pause
exit /b