Thursday, 4 March 2010

Command line script to zip and unzip files

In Windows XP, and Vista (possibly others) you have the ability to right-click a folder and compress it using some sort of inbuilt zip mechanism.  But how do you access the same functionality from the command line?

One way is to use scripts.  Here is the code for two files which I call zip.vbs:

FolderToZip = Wscript.Arguments(0)
zipFile = Wscript.Arguments(1)
Set sa = CreateObject("Shell.Application")
Set zip= sa.NameSpace(zipFile)
Set Fol=sa.NameSpace(FolderToZip)
zip.CopyHere Fol.Items, 16
Do Until zip.Items.Count = Fol.Items.Count
  WScript.Sleep 1000
Loop
 
and unzip.vbs:
 
pathToZipFile=Wscript.Arguments(0)
extractTo=Wscript.Arguments(1)
set sa = CreateObject("Shell.Application")
set filesInzip=sa.NameSpace(pathToZipFile).items
sa.NameSpace(extractTo).CopyHere(filesInzip)
 
To execute them the syntax is as follows:
 
cscript zip.vbs <folder_to_zip> <zip_file>
cscript unzip.vbs <zip_file> <folder_to_extract_to>
 
E.g:
 
cscript zip.vbs C:\Users\Richard\stuff C:\stuff.zip
cscript unzip.vbs C:\stuff.zip C:\Users\folder