在 Windows 批处理脚本的 for 循环中未通过“查找”命令获得所需的输出

Posted

技术标签:

【中文标题】在 Windows 批处理脚本的 for 循环中未通过“查找”命令获得所需的输出【英文标题】:Not getting the required output through "find" command in a for loop in Windows Batch Scripting 【发布时间】:2021-07-12 14:30:51 【问题描述】:

我的要求很简单,我只想扫描当前目录中的所有文件以查找特定字符串,如果找到该字符串,我只想显示“找到字符串”,否则显示“找不到字符串”

    @ECHO OFF
    for %%f in (C:\Users\aalvoor\Desktop\BatchScript\*) do (
    echo File is %%f
    find /c "defaultModel" %%f >NUL
    if %errorlevel% equ 1 (echo File is notfound) else (echo String is found)
    )

但问题是当我没有将它放入 for 循环时它可以工作,但是当我出于某种原因将它放入 for 循环中时,我收到一条消息 String is found which is not true.

【问题讨论】:

我建议打开command prompt,运行if /? 并阅读输出帮助,该帮助已在第一页解释了用于评估前运行命令或可执行文件的退出代码的推荐语法。所以使用if errorlevel 1 而不是if %errorlevel% equ 1 并且代码有效,您不必考虑延迟扩展。另见single line with multiple commands using Windows batch file 和this answer about dynamic variables 的第 4 章。 非常感谢大家..如果错误级别有效...而且不必使用延迟变量扩展逻辑,为此苦苦挣扎了一个多星期。实际使用了 Mofo 给出的评论.. 那么如何将其标记为接受的答案? 【参考方案1】:

使用条件运算符&&||

&& 是如果errorlevel equ 0

|| 是如果errorlevel neq 0

@echo off
for %%f in ("%userprofile%\Desktop\BatchScript\*") do (
    echo File is %%f
    find /c "defaultModel" %%f >nul 2>&1 && echo String found || echo String NOT found
)

【讨论】:

以上是关于在 Windows 批处理脚本的 for 循环中未通过“查找”命令获得所需的输出的主要内容,如果未能解决你的问题,请参考以下文章

for循环中未处理的异常

Windows bat脚本——for循环用法详解

Windows - for 循环中的 findstr(文件内容)

FOR 循环空间和处理

如何在批处理文件脚本的循环中打印程序的返回值?

Sonarqube 抱怨 for 循环中未使用的变量 [重复]