【问题标题】:How to create a batch file that checks if EXACTLY four specific files/folders exist in a folder?如何创建一个批处理文件来检查文件夹中是否存在四个特定的文件/文件夹?
【发布时间】:2021-10-13 03:50:56
【问题描述】:

我正在编写一个简单的批处理文件,它需要执行其操作 IFF(当且仅当)在特定文件夹中恰好存在 2 个文件和 2 个文件夹。文件名和文件夹名必须完全匹配,这样比较容易。

在伪代码中是:

IFF folder `FOO` contains (file `a.txt` AND file `b.txt` AND folder `f1` AND folder `f2`) THEN ...

顺便说一句,THEN ... 后面的代码全部完成。没问题。

这是我的代码:

IF EXIST a.txt goto good1
goto done
:good1
IF EXIST b.txt goto good2
goto done
:good2
IF EXIST f1 goto good3
goto done
:good3
IF EXIST b.txt goto good4
goto done
:good4
echo requirements met
:done

我可以使用IF EXIST 来处理IFFIF 部分(IF 和ONLY IF),但是如何确保文件夹FOO 中不存在其他文件/文件夹?

理想情况下,我希望保持简单,而不会创建由管道或stdout 重定向到文件引起的临时文件。

【问题讨论】:

    标签: windows if-statement batch-file conditional-statements


    【解决方案1】:

    这里有一个方法。我们首先对文件进行计数,然后对文件进行测试。

    @echo off & set cnt=0
    for /f %%i in ('dir /b') do set /a cnt+=1
    if %cnt% equ 4 if exist f1 if exist f2 if exist dir1 if exist dir2 echo All Good!
    

    以及一些轻微的错误生成:

    @echo off & set cnt=0
    for /f %%i in ('dir /b ^| findstr /v "%0"') do set /a cnt+=1
    if not %cnt% equ 4 echo oops, too many files/dirs, I count %cnt% && goto :eof
    if exist f1 if exist f2 if exist dir1 if exist dir2 echo All good && goto :eof
    echo one or more files do not match your if statement
    

    最后一种方法是使用find 来不使用for 循环。

    @echo off
    dir /b | find /c /v "" | findstr "\<4\>"
    if errorlevel 1 echo oops, too many files/dirs, I count %cnt% && goto :eof
    if exist f1 if exist f2 if exist dir1 if exist dir2 echo All good && goto :eof
    echo one or more files do not match your if statement
    

    来自这个答案的 cmets 的注释:

    1. @echo off &amp; set cnt=0 被集成到一行中只是为了减少行数。没有其他原因。
    2. findstr /v "%0" 仅在批处理文件本身可能位于同一文件夹中时才需要,因为该命令只是将批处理文件本身排除在文件计数中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-23
      • 1970-01-01
      • 2014-02-18
      • 1970-01-01
      • 2023-01-10
      • 1970-01-01
      • 2021-08-12
      • 2023-02-01
      相关资源
      最近更新 更多