9

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
Cheetah
  • 13,785
  • 31
  • 106
  • 190
  • [check this](http://stackoverflow.com/questions/28043589/) the zip utility is written in JScript but it you can call it as external process or if you put it in wsh file with your vbscript code. – npocmaka Jan 31 '15 at 11:09

3 Answers3

13

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
Community
  • 1
  • 1
Panayot Karabakalov
  • 3,109
  • 3
  • 19
  • 28
  • Above code working fine but after creating zip file not able to copy the file into it ..saying access denied. Manually also I tried opening the file getting same error. Please suggest – sanjeeb Jul 04 '17 at 12:31
1

Check your argument. folder must be the path to the object you want to put into the zip file. If it's a folder object you have to use folder.Path, because the default method of folder objects is Name, and CopyHere can't find the object with just the name.

You could add some debugging statements to your function to check that:

WScript.Echo TypeName(folder)
If fso.FolderExists(folder) Then
  WScript.Echo folder & " exists."
Else
  WScript.Echo folder & " doesn't exist."
End If
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
0

you could call an external zip file via %comspec%

oShell.Run "%comspec% /c c:\windows\7za.exe a " & oFile &".zip " & oFile & " -tzip",,True

Source http://www.scriptlook.com/zip-large-files-in-a-directory-2/

flydean
  • 16
  • 1