我有一个脚本可以删除过时的文件,但我想升级它并且我被卡住了。
On Error Resume Next
Set objShell = Wscript.CreateObject("Wscript.Shell")
Set oFileSys = WScript.CreateObject("Scripting.FileSystemObject")
sRoot = "C:\Users\admin\Desktop\LOGS\test"
today = Date
nMaxFileAge = 1
DeleteFiles(sRoot)
Function DeleteFiles(ByVal sFolder)
Set oFolder = oFileSys.GetFolder(sFolder)
Set aFiles = oFolder.Files
Set aSubFolders = oFolder.SubFolders
For Each file in aFiles
dFileCreated = FormatDateTime(file.DateCreated, "2")
If DateDiff("d", dFileCreated, today) > nMaxFileAge Then
objShell.Popup "Old file will be deleted after clicking ok",, "Warning"
file.Delete(True)
End If
Next
For Each folder in aSubFolders
DeleteFiles(folder.Path)
Next
我通过添加
升级了此脚本objShell.Popup "Old file will be deleted after clicking ok",, "Warning"
这个弹出框但当然现在我必须单击OK,因为要删除多少个文件......
我想只有一次这个弹出窗口,然后点击OK后,一切都会被自动删除。
答案 0 :(得分:0)
首先:使用当前代码,无论您是否执行此操作,都将删除该文件,或者单击“确定”。您需要检查实际点击了哪个按钮并做出相应的反应。您可能还需要MsgBox
使用"是"和"不"按钮而不是弹出窗口。
res = MsgBox("Delete files?", vbExclamation + vbYesNo, "Warning")
If res = vbYes Then
file.Delete True
End If
为避免必须单独确认每个文件,您需要在循环之前移动确认对话框:
res = MsgBox("Delete files?", vbExclamation + vbYesNo, "Warning")
If res = vbYes Then
For Each file in aFiles
If DateDiff("d", file.DateCreated, today) > nMaxFileAge Then
file.Delete True
End If
Next
End If
如果您只想在找到符合条件的文件时要求确认,您可以使用标志变量来指示是否删除文件:
Dim doDelete
For Each file in aFiles
If DateDiff("d", file.DateCreated, today) > nMaxFileAge Then
If IsEmpty(doDelete) Then
res = MsgBox("Delete files?", vbExclamation + vbYesNo, "Warning")
If res = vbYes Then
doDelete = True
Else
doDelete = False
End If
End If
If doDelete Then file.Delete True
End If
Next
或者您可以在列表中收集匹配的文件,并在要求确认后处理该列表:
Set toBeDeleted = CreateObject("System.Collections.ArrayList")
For Each file in aFiles
If DateDiff("d", file.DateCreated, today) > nMaxFileAge Then
toBeDeleted.Add file
End If
Next
res = MsgBox("Delete files?", vbExclamation + vbYesNo, "Warning")
If res = vbYes Then
For Each file in toBeDeleted
file.Delete True
Next
End If
答案 1 :(得分:0)
解决了问题!
继承人解决方案:
Dim bConfirmed
bConfirmed = False
For Each file in aFiles
If DateDiff("d", dFileCreated, today) > nMaxFileAge Then
If Not bConfirmed Then
objShell.Popup "Old file will be deleted after clicking ok",,"Warning"
bConfirmed = True
End If
file.Delete(True)
End If
他只询问一次(如果有任何过时的文件)并且不为每个文件重复提问。