【问题标题】:Batch-Script: Search subfolders, find file, delete all else批处理脚本:搜索子文件夹、查找文件、删除所有其他内容
【发布时间】:2018-07-17 07:47:06
【问题描述】:

我一直在尝试解决这个问题,并且我一直在网上大量搜索,但我还没有找到正确的答案。 所以这是我的问题:

我想创建一个批处理文件,它搜索某个目录的所有子文件夹,找到一个特定文件,然后删除搜索文件所在文件夹中除该文件之外的所有内容。

到目前为止,我想出的是:

cmd /k for /f %%a IN ('dir /b /s Neuer') do if not [%%a] == [index.txt] del /q %%a

但这只会删除每个子文件夹中的每个文件——这不是我想要的。

谁能帮忙?

【问题讨论】:

  • 重新思考你的逻辑:你被删除的每一个不是index.txt的文件;因为您使用的是dir /B /S%%a 返回完整路径,所以没有什么会等于index.txt。然后 rmove cmd /K 因为它没用,并在 for /F 之后添加 "delims=" 以防止包含空格的路径出现问题...

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


【解决方案1】:
    @echo off

    setlocal

    if "%~2" == "" (
      echo/Usage: %~nx0 ^<directory^> ^<file^>
      echo/
      echo/%~nx0 will search the given ^<directory^> and its subdirectories
      echo/looking for ^<file^>. If the ^<file^> is found, then all the other
      echo/files and subdirectories in the same directory as ^<file^> will be
      echo/deleted. If more than one ^<file^> is found then this action is
      echo/repeated for all matches. Wildcards are not accepted; ^<file^> can
      echo/be the name of either a file or a directory.
      exit /b
    )

    if not exist "%~1\" (
      echo/%nx0: "%~1" does not exist or is not a directory
      exit /b
    )

    set "TARGETNAME=%~2"

    for /r "%~1" %%t in (*) do call :checkFile "%%~t"
    for /r "%~1" %%t in (.) do call :checkDir "%%~t"

    exit /b

:checkFile

    if not "%~nx1" == "%TARGETNAME%" exit /b
    echo/* Found "%~1"
    echo/  - Deleting files in directory "%~dp1" . . .
    for %%f in ("%~dp1*") do call :delFile "%%f"
    echo/  - Deleting directories in directory "%~dp1" . . .
    for /d %%d in ("%~dp1*") do call :delDir "%%d"
    exit /b

:checkDir

    set "TESTNAME=%~1"
    call :checkFile "%TESTNAME:~0,-2%"
    exit /b

:delFile

    if "%~nx1" == "%TARGETNAME%" exit /b

    echo/    : del "%~1"
    rem        del "%~1"
    exit /b

:delDir

    if "%~nx1" == "%TARGETNAME%" exit /b

    echo/    : rd /q /s "%~1"
    rem        rd /q /s "%~1"
    exit /b

注意事项:

  1. 在生产中,当然会做一些错误检查。

    • 可能有些文件因为具有只读属性而无法删除,或者运行脚本的用户没有相应的权限,或者正在使用中等等。

    • 可能某些目录无法删除,原因类似,或者因为它们包含隐藏文件,或者因为它们包含无法删除的文件。

  2. 脚本查找具有给定名称的文件目录;很容易看出如何将搜索限制为仅文件。

  3. 该脚本将对与给定名称匹配的所有文件或目录执行其工作。

  4. 如此处所示,脚本实际上并没有删除任何内容,它只是打印要删除的内容。要使其真正删除,只需删除delrd 前面的rem

【讨论】:

    【解决方案2】:

    正是针对此类问题,发明了forfiles 命令:

    ForFiles explanation

    【讨论】:

    • 谢谢,我不知道!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    • 1970-01-01
    • 2021-11-08
    • 2013-10-06
    • 1970-01-01
    • 2018-09-16
    相关资源
    最近更新 更多