Search code examples
vbscriptzip

Zip a folder up


I am trying to ZIP up a folder in VBScript and it doesn't seem to work. I'm certain I am creating the header file correctly.

It creates the actual file correctly, just doesn't zip the folder.

Anyone got any ideas:

Sub ArchiveFolder (folder)

    Dim fso, wShell, sApp, zipFile

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set wShell = CreateObject("WScript.Shell")  
    Set sApp = CreateObject("Shell.Application")
    Set zipFile = fso.CreateTextFile(folder & ".zip")

    ' Write zip file header.
    zipFile.Write "PK" & Chr(5) & Chr(6) & String(18, 0)
    zipFile.Close

    sApp.NameSpace(folder & ".zip").CopyHere folder

End Sub

Solution

  • The answer I found here. The magic is in the last Do..Loop where the script wait the Shell to do it job.

    ArchiveFolder "sub\foo.zip", "..\baz"
    
    Sub ArchiveFolder (zipFile, sFolder)
    
        With CreateObject("Scripting.FileSystemObject")
            zipFile = .GetAbsolutePathName(zipFile)
            sFolder = .GetAbsolutePathName(sFolder)
    
            With .CreateTextFile(zipFile, True)
                .Write Chr(80) & Chr(75) & Chr(5) & Chr(6) & String(18, chr(0))
            End With
        End With
    
        With CreateObject("Shell.Application")
            .NameSpace(zipFile).CopyHere .NameSpace(sFolder).Items
    
            Do Until .NameSpace(zipFile).Items.Count = _
                     .NameSpace(sFolder).Items.Count
                WScript.Sleep 1000 
            Loop
        End With
    
    End Sub