Zipping a large folder fails

我只是一个虾纸丫 提交于 2019-11-27 16:30:36

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!