需要一个 bat 文件来删除具有唯一名称的文件夹

需要一个 bat 文件来删除具有唯一名称的文件夹

因此,我正在处理一个 bat 文件来删除一个文件,然后查找并删除一个文件夹。

它可以顺利删除文件,但我在删除其余文件时遇到了问题。我尝试删除的文件夹每次都有不同的名称,但每次文件夹名称开头都包含相同的关键字。

下面这行代码用于查找有问题的文件夹,但我不知道找到后如何真正删除该文件夹。

dir C:\location\*keyword*.* /S

任何帮助将不胜感激。

PS:我可以接受非为 .bat 制作的代码,但如果不是,则需要将其设置为在启动时运行。

我使用了以下两种方法(不是同时使用)来删除找到的文件

del C:\location\*keyword*.* /S 
rd  C:\location\*keyword*.* /S 

答案1

放在DIR使用命令/B切换也FOR /F循环然后使用批量替换仅显示驱动器号小路在递归中找到的文件的文件夹DIR使用“keyword“和通配符(如示例中所示),然后将其传递给RD使用命令/Q/S开关。


批处理脚本

 @ECHO ON

 SET keyword=<My Keyword>
 SET searchfolder=C:\Folder\<StartHere>

 CD /D "%searchfolder%"
 FOR /F "TOKENS=*" %%F IN ('DIR /S /B "*%keyword%*.*"') DO RD /S /Q "%%~DPF"

 GOTO EOF

更多资源

  • 为/F

  • 批量替换 (FOR /?)

    此外,FOR 变量引用的替换功能也得到了增强。现在您可以使用以下可选语法:

    %~I         - expands %I removing any surrounding quotes (")
    %~fI        - expands %I to a fully qualified path name
    %~dI        - expands %I to a drive letter only
    %~pI        - expands %I to a path only
    %~nI        - expands %I to a file name only
    %~xI        - expands %I to a file extension only
    %~sI        - expanded path contains short names only
    %~aI        - expands %I to file attributes of file
    %~tI        - expands %I to date/time of file
    %~zI        - expands %I to size of file
    %~$PATH:I   - searches the directories listed in the PATH
                   environment variable and expands %I to the
                   fully qualified name of the first one found.
                   If the environment variable name is not
                   defined or the file is not found by the
                   search, then this modifier expands to the
                   empty string
    

测试脚本

您需要按 移动Enter到每个命令,但在您按下 Enter,请务必阅读整个屏幕以查看所有发现的内容,以确认这是您期望删除的内容,等等。

 @ECHO ON

 SET keyword=<My Keyword>
 SET searchfolder=C:\Folder\<StartHere>

 CD /D "%searchfolder%"

 ECHO *** Below are the folder path and file names of the files matching "*%keyword%*.*" 

 DIR /S /B "*%keyword%*.*"

 PAUSE
 CLS

 ECHO *** Below are the folder paths that will be deleted  where files were found to reside matching the pattern "*%keyword%*.*"

 FOR /F "TOKENS=*" %%F IN ('DIR /S /B "*%keyword%*.*"') DO ECHO RD /S /Q "%%~DPF"

 PAUSE

 GOTO EOF

相关内容