Batch Script – Zip/Compress Files Without Calling Any Third-Party Applications

While writing another batch script the last several days, I found out that you cannot zip or compress files or folders natively from the command line without having additional third-party software or PowerShell. After a while of scouring the forums, I came up with this pure batch solution that uses VB script.

Basically, from this chunk of code in a single batch file, we can both generate the VB script, zip up whatever files we want, and then just delete the VB script when we’re done. Within the batch file, we can just call on the VB script using “CScript” and it works pretty much like any other function in any other programming language.

@ECHO OFF

:: Since there is no built-in way to zip/unzip files in Windows, we have to use an add-on VB script.
:: This will auto-create the zip.vbs script in the current directory the batch file is being ran from.
:: "%~dp0" Is an environment variable that gets the full path to the current batch file's directory.
@ECHO InputFolder = WScript.Arguments(0)>>"%~dp0zip.vbs"
@ECHO ZipFile = WScript.Arguments(1)>>"%~dp0zip.vbs"
@ECHO CreateObject("Scripting.FileSystemObject").CreateTextFile(ZipFile, True).Write "PK" ^& Chr(5) ^& Chr(6) ^& String(18, vbNullChar)>>"%~dp0zip.vbs"
@ECHO Set objShell = CreateObject("Shell.Application")>>"%~dp0zip.vbs"
@ECHO Set source = objShell.NameSpace(InputFolder).Items>>"%~dp0zip.vbs"
@ECHO objShell.NameSpace(ZipFile).CopyHere(source)>>"%~dp0zip.vbs"
@ECHO wScript.Sleep 2000>>"%~dp0zip.vbs"

:: The path to our new zipper script dealie whopper
SET ZScriptPath="%~dp0zip.vbs"

Then you can call on it later as if it were a function like this:

CScript //nologo %ZScriptPath% "SourceFolderPathToZip" "DestinationZipFilePath.zip"

When you’re done zipping up files and you don’t want to leave the zip.vbs script lying around somewhere, you can issue this command:

DEL /F /Q /S %ZScriptPath%

Leave a Reply