这是我的函数不起作用。它永远不会到达删除调用,因为 if 语句永远不会计算为 true,而且我不明白为什么。
Function DeleteOldFolders(root, maxAgeInDays)
Dim fso, ofolder, subFolders
Set fso = CreateObject ("Scripting.FileSystemObject")
If fso.FolderExists(root) Then
Set ofolder = fso.GetFolder(root)
Set subFolders = ofolder.SubFolders
For Each folder in subFolders
createdDate = FormatDateTime(folder.DateCreated, "2")
If (DateDiff("d", createdDate, Date) > maxAgeInDays) Then
objFSO.DeleteFolder folder, True
End If
Next
End If
Set objFSO = Nothing
End Function
最佳答案
没有删除任何内容的原因可能是您定义了fso
Set fso = CreateObject ("Scripting.FileSystemObject")
然后使用objFSO
objFSO.DeleteFolder folder, True
并在脚本中的其他位置添加On Error Resume Next
(永远不要永远使用它,除非你确切知道你在做什么执行并且有合理的错误处理代码)。
一些旁注(与实际问题无关,但值得考虑):
- 始终使用
Option Explicit
。无一异常(exception)。 - 您可以直接在
DateDiff()
中使用folder.DateCreated
。无需格式化该值。 - 您的函数不会返回任何内容,因此您最好将其设为过程。
您的过程的简化版本可能如下所示。
Sub DeleteOldFolders(root, maxAgeInDays)
Dim fso, folder
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FolderExists(root) Then
For Each folder in fso.GetFolder(root).SubFolders
If DateDiff("d", folder.DateCreated, Date) > maxAgeInDays Then
folder.Delete True
End If
Next
End If
Set fso = Nothing
End Sub
关于vbscript - 删除超过特定期限的文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15072155/