Zipping a large folder fails

前端 未结 1 1772
清歌不尽
清歌不尽 2020-12-04 04:14

I am trying to archive logs to capture an intermittent fault where my logs are regularly overwritten. I wish to archive the logs to ensure I capture the required event.

相关标签:
1条回答
  • 2020-12-04 04:30

    Your code is a little more complicated than it needs to be, but it works in principle. What's causing the failures you're experiencing with large folders is the fixed 2 second delay at the end:

    WScript.Sleep 2000
    

    CopyHere runs asynchronously, meaning that it runs in the background while the script continues. However, after 2 seconds delay the script terminates (and the Shell.Application instance with it), whether CopyHere has finished or not. When you have numerous/large files the processing may well take more than 2 seconds.

    That's why your script works fine for small folders, but not for large ones. The copying simply isn't finished when the script terminates after 2 seconds.

    To avoid this, replace the fixed delay with a check that compares the number of processed files to the total file count:

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set app = CreateObject("Shell.Application")
    
    zipfile = "C:\Temp\logs_" & Day(Date) & Month(Date) & Year(Date) & ".zip"
    fldr    = "C:\Temp\sample"
    cnt     = fso.GetFolder(fldr).Files.Count
    
    'create a new empty zip file
    fso.OpenTextFile(zipfile, 2, True).Write "PK" & Chr(5) & Chr(6) _
      & String(18, Chr(0))
    
    'start copying the files from the source folder to the zip file
    Set zip = app.NameSpace(zipfile)
    zip.CopyHere app.NameSpace(fldr).Items     '<- runs asynchronously!
    
    'wait for CopyHere to finish
    Do
      WScript.Sleep 100
    Loop Until zip.Items.Count = cnt
    
    0 讨论(0)
提交回复
热议问题