删除文件夹时如何暂停VBS脚本?

时间:2009-11-20 12:54:17

标签: vbscript

我正在为SyncBack编写一个VBScript(备份工具),我正在删除旧版本的备份。

    '' # if current version is greater than the total allowed number of versions,
    '' # delete the oldest folder
    If versionNumber > totalVersions Then
        delDirNum = versionNumber - totalVersions
        If delDirNum > 0 Then
            DelFoldername = containerFileOrFolder & "\" & delDirNum & "_"
               '' " # Ignore this line SO Prettify doesn't do VB very well. 
            If fso.FolderExists(DelFoldername) = True Then
                WScript.Echo "Deleting: <" & DelFoldername & ">"
                Set oFolder = objFileSystem.GetFolder(DelFoldername)
                oFolder.Delete()
                WScript.Sleep 2000
                If fso.FolderExists(DelFoldername) = False Then
                    WScript.Echo "Deleted <" & DelFoldername & "> successfully"
                Else
                    WScript.Echo "Could not delete <" & DelFoldername & ">"
                End If
            End If
        End If
    End If

但是,偶尔我要删除的文件夹(包含旧备份)需要更长时间才能删除 WScript.Sleep 2000 上的2秒,我想知道是否有办法使脚本等到文件夹被删除之后才打印出“已成功删除&lt; foldername&gt;”。

理想情况下,我喜欢这样的事情:

While oFolder.IsDeleting() Then
    WScript.Echo "Still deleting..."
    WScript.Sleep 2000
Loop

但我很清楚,情况可能并非如此。

4 个答案:

答案 0 :(得分:3)

While fso.FolderExists(DelFoldername)
   WScript.Echo "Still deleting"
   WScript.Sleep 1000
Wend

答案 1 :(得分:2)

您可以将删除移动到自己的功能中并添加超时。因此,如果文件夹未在合理的时间内删除,则函数将返回而不删除文件夹。像这样:

Function DeleteFolder(Folder, Timeout)
'Folder is the full file path of the folder
'Timeout is the amount of time to wait for the folder to be deleted (in seconds).
    On Error Resume Next
    Set fso = CreateObject("Scripting.FileSystemObject")
    If fso.FolderExists(Folder) Then
        fso.DeleteFolder Folder, True
        start = Now()
        do while fso.FolderExists(Folder) AND DateDiff("s",start,Now()) < Timeout
            wscript.sleep 1000
        Loop
    End If
    If fso.FolderExists(Folder) Then
        DeleteFolder = False
    Else 
        DeleteFolder = True
    End If
End Function 

然后像这样调用函数

If DeleteFolder("C:\New Folder", 5) Then
    Wscript.Echo "Folder Deleted"
Else
    Wscript.Echo "Folder could NOT be deleted" 
End If

警告:不建议使用 On Error Resume Next
此命令将导致忽略所有错误,并且只能在成人监督下使用。

副作用可能包括:脚本其他部分的奇怪错误,意外的脚本动作,头痛,头晕,困惑,愤怒或突然的诅咒冲动。在极少数情况下,这种命令会导致眼睛和耳朵出血。使用此命令可能会导致头发和失业。

答案 2 :(得分:1)

使用计数器循环睡眠,注意假定CScript主机使“静止删除”消息更加可调整。示例中的延迟是30秒。

Dim loopCount : loopCount = 0
WScript.StdOut.Write "Deleting ."
Do While fso.FolderExists(DelFoldername) And loopCount < 30
   WScript.Sleep 1000
   WScript.StdOut.Write "."
   loopCount = loopCount + 1
Loop
WScript.StdOut.Write vbCrLf
If fso.FolderExists(DelFolderName) Then
   '' # Do stuff due to failure.
End If

答案 3 :(得分:0)

为什么不继续检查文件夹是否仍然存在,并在文件夹消失后退出?

'做     '如果文件夹不存在,请退出Do '循环