批处理脚本:如何连接两个条件来删除目录?

时间:2017-10-30 21:47:39

标签: batch-file directory subdirectory

我在目录中工作,希望我的批处理脚本根据以下两个条件删除所有子目录:

  1. 子目录的名称以foo开头。
  2. 该子目录最后修改超过14天前。
  3. 到目前为止,我可以根据条件1删除子目录,我可以根据条件2选择目录:

    FOR /D %%i IN (C:\path\foo*) DO (rd /s /q "%%i")
    

    Forfiles /d -14
    

    我如何加入这两个条件?

    提前致谢。

2 个答案:

答案 0 :(得分:1)

有些事情(比如使用日期)需要使用VBScript而不是批处理命令。可能有一种方法可以在.bat中执行您想要的操作,但在.vbs中组合多个AND是微不足道的。以下是删除子文件夹的示例。您只需要为" C:\ path \ foo *。

提供正则表达式
Dim oFSO, oFolder, oFolderCollection, iDaysOld, Date1, wsh, regex

iDaysOld = 14
Date1 = Date()

'Create FileSystemObject object to access the file system.

Set wsh = WScript.CreateObject("WScript.Shell")
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set regex = new regexp
regex.IgnoreCase = True
regex.Pattern = {sorry but you'll need to figure out the regex here}

'Get Folder object and Files
Set oFolder = oFSO.GetFolder(wsh.ExpandEnvironmentStrings(path)) 
Set oFolderCollection = oFolder.SubFolders

'Walk through each file in this folder collection. 
For each folder in oFolderCollection

If (folder.DateModified <= (Date() - iDaysOld)) And (regex.Execute(folder.path)) Then

' WARNING The following line will delete the folder and any subfolders or files. True means that it will delete read only too
folder.Delete(True)

End If
Next

'Remove the following line when running in production
'MsgBox "Deleted files.", vbOKOnly + vbInformation

'Clean up
Set oFSO = Nothing
Set oFolder = Nothing
Set oFolderCollection = Nothing
'End

答案 1 :(得分:1)

怎么样?
forfiles /P C:\path\ /M foo* /S /D -14 /C "cmd /c if @isdir==TRUE echo rd /s /q @file"  

使用forfiles进行日期选择,递归搜索,名称模式以及仅选择文件夹的条件。