325

In Windows you can zip some files by

right click → Send toCompressed (zipped) folder

And unzip by double clicking on the .zip file and extract the files.

Is there a way to apply those abilities from a script (.bat file) without the need to install any third-party software?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Roee Gavirel
  • 18,955
  • 12
  • 67
  • 94
  • 1
    Clues here: http://stackoverflow.com/questions/30211/can-windows-built-in-zip-compression-be-scripted and http://stackoverflow.com/questions/1021557/how-to-unzip-a-file-using-the-command-line – doctorlove Jul 09 '13 at 10:41
  • use 7zip https://sevenzip.osdn.jp/chm/cmdline/syntax.htm – The Student Sep 01 '17 at 21:57
  • This question [was comprehensibly answered on Super User in 2010](https://superuser.com/questions/110991/can-you-zip-a-file-from-the-command-prompt-using-only-windows-built-in-capabili/111266#111266), 2 1/2 years prior. – Peter Mortensen Jul 11 '19 at 18:15

18 Answers18

191

To expand upon Steven Penny's PowerShell solution, you can incorporate it into a batch file by calling powershell.exe like this:

powershell.exe -nologo -noprofile -command "& { Add-Type -A 'System.IO.Compression.FileSystem'; [IO.Compression.ZipFile]::ExtractToDirectory('foo.zip', 'bar'); }"

As Ivan Shilo said, this won't work with PowerShell 2, it requires PowerShell 3 or greater and .NET Framework 4.

Zombo
  • 1
  • 62
  • 391
  • 407
Jason Duffett
  • 3,428
  • 2
  • 23
  • 23
  • 1
    Actually, this was made available in .NET 4.5. – qJake Apr 30 '15 at 19:00
  • 11
    For those (like me) who wonder how to extract into the actual directory (instead of creating a new directory) simply set the target parameter to `'.'`, e.g.: `powershell.exe -nologo -noprofile -command "& { Add-Type -A 'System.IO.Compression.FileSystem'; [IO.Compression.ZipFile]::ExtractToDirectory('foo.zip', '.'); }"` – Munchkin Feb 01 '16 at 14:12
  • 1
    What is the purpose of `& {}`? With PS5 this works, too: `powershell.exe -nologo -noprofile -command "Add-Type -A 'System.IO.Compression.FileSystem'; [IO.Compression.ZipFile]::ExtractToDirectory('foo.zip', '.');"` – Roi Danton Nov 29 '17 at 09:57
148

If you have Java installed, you can compress to a ZIP archive using the jar command:

jar -cMf targetArchive.zip sourceDirectory

c = Creates a new archive file.

M = Specifies that a manifest file should not be added to the archive.

f = Indicates target file name.

Noam Manos
  • 15,216
  • 3
  • 86
  • 85
100

PowerShell 5.0

From Microsoft.PowerShell.Archive you can use:

E.g.:

  • Create result.zip from the entire Test folder:

    Compress-Archive -Path C:\Test -DestinationPath C:\result
    
  • Extract the content of result.zip in the specified Test folder:

    Expand-Archive -Path result.zip -DestinationPath C:\Test
    
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
  • 16
    This works great, thank you. For anyone ending up down here, you can use `powershell Compress-Archive -Path C:\SomeFile.ext -DestinationPath C:\SomeFile.zip` right from command line without needing to make a script (assuming you have Powershell v5 installed, which you can do at least going back to Windows 7). – Beems Jan 03 '17 at 20:14
  • 1
    Works great, add -Force option if you are planning on rerunning it. – Robin Salih Sep 13 '17 at 10:04
  • 1
    @Beems, Thank you! But I think you mad the path / destination the other way round? – Yiping Jun 29 '18 at 10:03
  • 1
    This works, but the archive is compressed differently then what happens if you use the windows explorer "Sent To -> compressed (zipped) folder" The powershell version is bigger and some programs can't extract – Eric Labashosky Nov 26 '19 at 22:04
  • Compress-Archive has a maximum file limit of 2GB on the input file – Sergei Rodionov May 28 '20 at 05:12
  • I'm also noticing a similar issue as @Eric. The compressed file is different from the one created using "Send To -> compressed (zipped) folder". – Gangula Jul 06 '22 at 08:48
87

Back in 2013, that was not possible. Microsoft didn't provide any executable for this.

See this link for some VBS way to do this. https://superuser.com/questions/201371/create-zip-folder-from-the-command-line-windows

From Windows 8 on, .NET Framework 4.5 is installed by default, with System.IO.Compression.ZipArchive and PowerShell available, one can write scripts to achieve this, see https://stackoverflow.com/a/26843122/71312

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Paul Chen
  • 1,873
  • 1
  • 16
  • 28
  • 1
    This isn't correct given that PS allows this and is pre-installed on Windows and is available via the command line. – Dan Atkinson Aug 14 '15 at 16:05
  • @DanAtkinson Then you're answering the wrong question; the question asked for a way to "apply those abilities from the command line" – Michael Mrozek Dec 02 '16 at 07:24
  • 6
    @MichaelMrozek Well "command line" refers generically to any command line, not specifically CMD/COMMAND, and PS definitely is a command line, as is bash, sh, rsh on *nix. But just to go one further, since you can run powershell from the command line, it does answer the question even if you want to believe that cmd/command is the one and only command line. – Robert McKee Jan 06 '17 at 18:21
  • 2
    It *was* possible back in 2013 (without installing any extra software). See [the Super User question](https://superuser.com/questions/110991/can-you-zip-a-file-from-the-command-prompt-using-only-windows-built-in-capabili/111266#111266). It has been possible since [Windows XP](http://en.wikipedia.org/wiki/Windows_XP) came out in 2001. The built-in ZIP functionality in Windows XP can be leveraged because it is exposed through a [COM interface](http://en.wikipedia.org/wiki/Component_Object_Model). – Peter Mortensen Jul 11 '19 at 18:09
37

It isn't exactly a ZIP, but the only way to compress a file using Windows tools is:

makecab <source> <dest>.cab

To decompress:

expand <source>.cab <dest>

Advanced example (from ss64.com):

Create a self extracting archive containing movie.mov:
C:\> makecab movie.mov "temp.cab"
C:\> copy /b "%windir%\system32\extrac32.exe"+"temp.cab" "movie.exe"
C:\> del /q /f "temp.cab"

More information: makecab, expand, makecab advanced uses

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • No, [it is not the only way to compress a file using Windows tools](https://stackoverflow.com/questions/17546016/how-can-you-zip-or-unzip-from-the-script-using-only-windows-built-in-capabiliti/24323413#comment100524315_17546190). – Peter Mortensen Jul 11 '19 at 18:25
32

Using 7-Zip:

Zip: you have a folder foo, and want to zip it to myzip.zip

"C:\Program Files\7-Zip\7z.exe" a  -r myzip.zip -w foo -mem=AES256

Unzip: you want to unzip it (myzip.zip) to current directory (./)

"C:\Program Files\7-Zip\7z.exe" x  myzip.zip  -o./ -y -r
phuclv
  • 37,963
  • 15
  • 156
  • 475
Monir
  • 1,402
  • 14
  • 16
  • 36
    Please notice the question: `without the need to install any 3rd party` – Roee Gavirel Jan 26 '16 at 06:32
  • 1
    @ Roland : By specifying this switch( -w), you can set the working directory where the temporary base archive file will be built. After the temporary base archive file is built, it is copied over the original archive; then, the temporary file is deleted. – Monir Feb 26 '17 at 18:15
  • @Monir understood. But why? Without the `-w` switch the temporary base archive will be in the same directory, so what do you gain by using `-w` as opposed to just not using that switch? – Roland Mar 06 '17 at 07:17
  • @Roland: Yes you are right . we are not gaining something until we want to specify a certain a path. – Monir Mar 10 '17 at 15:58
8

You can use a VBScript script wrapped in a BAT file. This code works on a relative PATH.

There isn't any need for any third-party tools or dependencies. Just set SOURCEDIR and OUTPUTZIP.

Filename: ZipUp.bat

echo Set fso = CreateObject("Scripting.FileSystemObject") > _zipup.vbs
echo InputFolder = fso.GetAbsolutePathName(WScript.Arguments.Item(0)) >> _zipup.vbs
echo ZipFile = fso.GetAbsolutePathName(WScript.Arguments.Item(1)) >> _zipup.vbs

' Create empty ZIP file.
echo CreateObject("Scripting.FileSystemObject").CreateTextFile(ZipFile, True).Write "PK" ^& Chr(5) ^& Chr(6) ^& String(18, vbNullChar) >> _zipup.vbs

echo Set objShell = CreateObject("Shell.Application") >> _zipup.vbs
echo Set source = objShell.NameSpace(InputFolder).Items >> _zipup.vbs
echo objShell.NameSpace(ZipFile).CopyHere(source) >> _zipup.vbs

echo ' Keep script waiting until compression is done
echo Do Until objShell.NameSpace( ZipFile ).Items.Count = objShell.NameSpace( InputFolder ).Items.Count >> _zipup.vbs
echo     WScript.Sleep 200 >> _zipup.vbs
echo Loop >> _zipup.vbs

CScript  _zipup.vbs  %SOURCEDIR%  %OUTPUTZIP%

del _zipup.vbs

Example usage

SET SOURCEDIR=C:\Some\Path
SET OUTPUTZIP=C:\Archive.zip
CALL ZipUp

Alternatively, you can parametrize this file by replacing the line CScript _zipup.vbs %SOURCEDIR% %OUTPUTZIP% with CScript _zipup.vbs %1 %2, in which case it can be even more easily called from by simply calling CALL ZipUp C:\Source\Dir C:\Archive.zip.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
PodTech.io
  • 4,874
  • 41
  • 24
  • The line which creates the initial zip file needs to be escaped otherwise it does not end up in the script. – cup Jul 20 '17 at 04:50
  • Yes, this is the way to go (like in [the Super User question](https://stackoverflow.com/questions/17546016/how-can-you-zip-or-unzip-from-the-script-using-only-windows-built-in-capabiliti/24323413#comment100524315_17546190)). – Peter Mortensen Jul 11 '19 at 18:27
  • Why re-write the VBS file again and again each time you use the command? – OMA Aug 08 '20 at 23:00
7

I've been looking to answer this exact question and from my research, DiryBoy's response seems to be accurate.

I found the compact.exe program compresses files but not to create a highly compressed file (or set of files). It is similar to the option you get when right clicking on a drive letter or partition in Windows. You get the option to do cleanup (remove temp files, etc) as well as compress files. The compressed files are still accessible but are just compressed to create space on a drive that is low on space.

I also found compress.exe which I did happen to have on my computer. It isn't natively on most windows machines and is part of the 2003 resource kit. It does make a zipped file of sorts but it is really more similar to files from a windows setup disk (has the underscore as the last character of the file extension or name). And the extract.exe command extracts those files.

However, the mantra is, if it can be done natively via the GUI then there is likely a way to do it via batch, .vbs, or some other type of script within the command line. Since windows has had the 'send to' option to create a zip file, I knew there had to be a way to do it via command line and I found some options.

Here is a great link that shows how to zip a file using windows native commands.

https://superuser.com/questions/110991/can-you-zip-a-file-from-the-command-prompt-using-only-windows-built-in-capabili

I tested it with a directory containing multiple nested files and folders and it worked perfectly. Just follow the format of the command line.

There is also a way to unzip the files via command line which I found as well. One way, just brings open an explorer window showing what the content of the zipped file is. Some of these also use Java which isn't necessarily native to windows but is so common that it nearly seems so.

https://superuser.com/questions/149489/does-windows-7-have-unzip-at-the-command-line-installed-by-default

How to unzip a file using the command line?

Community
  • 1
  • 1
LostUser
  • 103
  • 1
  • 1
  • No, [DiryBoy's response is *not* accurate](https://stackoverflow.com/questions/17546016/how-can-you-zip-or-unzip-from-the-script-using-only-windows-built-in-capabiliti/24323413#comment100524315_17546190) – Peter Mortensen Jul 11 '19 at 18:17
5

If you need to do this as part of a script then the best way is to use Java. Assuming the bin directory is in your path (in most cases), you can use the command line:

jar xf test.zip

If Java is not on your path, reference it directly:

C:\Java\jdk1.6.0_03\bin>jar xf test.zip
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
eddyoc
  • 667
  • 11
  • 16
4

I have a problem with all these solutions.

They're not exactly the same, and they all create files that have a slight size difference compared to the RMB --> send to --> compressed (zipped) folder when made from the same source folder. The closest size-difference I have had is 300 KB difference (script > manual), made with:

powershell Compress-Archive -Path C:\sourceFolder -CompressionLevel Fastest -DestinationPath C:\destinationArchive.zip

(Notice the -CompressionLevel. There are three possible values: Fastest, NoCompression & Optimal, (Default: Optimal))

I wanted to make a .bat file that should automatically compress a WordPress plugin folder I'm working on, into a .zip archive, so I can upload it into the WordPress site and test the plugin.

But for some reason it doesn't work with any of these automatic compressions, but it does work with the manual RMB compression, witch I find really strange.

And the script-generated .zip files actually break the WordPress plugins to the point where they can't be activated, and they can also not be deleted from inside WordPress. I have to SSH into the "back side" of the server and delete the uploaded plugin files themselves, manually. While the manually RMB-generated files work normally.

Sebastian Norr
  • 7,686
  • 2
  • 12
  • 17
3

This is an updated version to the answer provided by @PodTech.io

This version has all of the vbs code correctly escaped in the batch file. It's also created into a sub-routine, which can be called with a single line from anywhere in your batch script:

:: === Main code:

call :ZipUp "C:\Some\Path" "C:\Archive.zip"


:: === SubRoutines:

:ZipUp
::Arguments: Source_folder, destination_zip
(
    echo:Set fso = CreateObject^("Scripting.FileSystemObject"^)
    echo:InputFolder = fso.GetAbsolutePathName^(WScript.Arguments.Item^(0^)^)
    echo:ZipFile = fso.GetAbsolutePathName^(WScript.Arguments.Item^(1^)^)
    echo:
    echo:' Create empty ZIP file.
    echo:CreateObject^("Scripting.FileSystemObject"^).CreateTextFile^(ZipFile, True^).Write "PK" ^& Chr^(5^) ^& Chr^(6^) ^& String^(18, vbNullChar^)
    echo:
    echo:Set objShell = CreateObject^("Shell.Application"^)
    echo:Set source = objShell.NameSpace^(InputFolder^).Items
    echo:objShell.NameSpace^(ZipFile^).CopyHere^(source^)
    echo:
    echo:' Keep script waiting until compression is done
    echo:Do Until objShell.NameSpace^( ZipFile ^).Items.Count = objShell.NameSpace^( InputFolder ^).Items.Count
    echo:    WScript.Sleep 200
    echo:Loop
)>_zipup.vbs
CScript //Nologo _zipup.vbs "%~1" "%~2"
del _zipup.vbs
goto :eof
fsteff
  • 543
  • 5
  • 19
3

Shell.Application

With Shell.Application you can emulate the way explorer.exe zips files and folders The script is called zipjs.bat:

:: unzip content of a zip to given folder.content of the zip will be not preserved (-keep no).Destination will be not overwritten (-force no)
call zipjs.bat unzip -source C:\myDir\myZip.zip -destination C:\MyDir -keep no -force no

:: lists content of a zip file and full paths will be printed (-flat yes)
call zipjs.bat list -source C:\myZip.zip\inZipDir -flat yes

:: lists content of a zip file and the content will be list as a tree (-flat no)
call zipjs.bat list -source C:\myZip.zip -flat no

:: prints uncompressed size in bytes
zipjs.bat getSize -source C:\myZip.zip

:: zips content of folder without the folder itself
call zipjs.bat zipDirItems -source C:\myDir\ -destination C:\MyZip.zip -keep yes -force no

:: zips file or a folder (with the folder itslelf)
call zipjs.bat zipItem -source C:\myDir\myFile.txt -destination C:\MyZip.zip -keep yes -force no

:: unzips only part of the zip with given path inside
call zipjs.bat unZipItem -source C:\myDir\myZip.zip\InzipDir\InzipFile -destination C:\OtherDir -keep no -force yes
call zipjs.bat unZipItem -source C:\myDir\myZip.zip\InzipDir -destination C:\OtherDir 

:: adds content to a zip file
call zipjs.bat addToZip -source C:\some_file -destination C:\myDir\myZip.zip\InzipDir -keep no
call zipjs.bat addToZip -source  C:\some_file -destination C:\myDir\myZip.zip

MAKECAB

Makecab is the default compressing tool coming with windows. Though it can use different compression algorithms (including zip) file format is always a .cab file. With some extensions it can be used on linux machines too.

compressing a file:

makecab file.txt "file.cab"

Compressing an entire folder needs a little bit more work. Here a directory is compressed with cabDir.bat:

call cabDir.bat ./myDir compressedDir.cab

Uncompressing is rather easy with expand command:

EXPAND cabfile -F:* .

More hackier way is by creating self-extracting executable with extrac32 command:

copy /b "%windir%\system32\extrac32.exe"+"mycab.cab" "expandable.exe"
call expandable.exe

TAR

With the build 17063 of windows we have the tar command:

::compress directory
tar -cvf archive.tar c:\my_dir
::extract to dir
tar -xvf archive.tar.gz -C c:\data

.NET tools

.net (and powershell) offers a lot of ways to compress and uncompress files. The most straightforward is with gzip stream. The script is called gzipjs.bat:

::zip
call gzipjs.bat -c my.file my.zip
::unzip
call gzipjs.bat -u my.zip my.file
npocmaka
  • 55,367
  • 18
  • 148
  • 187
2

This one worked for me (in 2021):

tar -xf test.zip

This will unzip the test in the current directory.

Irfan wani
  • 4,084
  • 2
  • 19
  • 34
2

Newer windows builds include tar.exe.
tar.exe can be used in the cmd or windows batch files.

//Compress a folder:
tar -caf aa.zip c:\aa
Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185
1

You can use this command to compress an entire folder and subfolders

compact /c /s "C:\Temp\my_folder" /I /Q

To Decompress

compact /u /s:"C:\Temp\my_folder" /I /Q

While c stands for compress and u for decompress

0

Adding upon @Jason Duffett's answer and its comments, here's a script that gets input and output (file name and directory name, respectively) from the user:

@echo off
set input=%1
set output=%2
powershell.exe "Add-Type -A 'System.IO.Compression.FileSystem'; [IO.Compression.ZipFile]::ExtractToDirectory('%input%', '%output%');"

Usage:

unzip.bat path\to\file.zip path\to\output\directory
OfirD
  • 9,442
  • 5
  • 47
  • 90
  • The PowerShell from a batch file approach has 2 little issues: 1. There is no text output during the process to see the progress of what is being extracted. 2. The process can't be interrupted with Ctrl+C or any other key combination. Only killing the "powershell.exe" process from the Task Manager stops it. – OMA Aug 08 '20 at 23:04
0

I found a way to unzip a zip file with a batch file:

@echo off
::unziper
set /p zip=zip:
powershell -Command "Expand-Archive %zip%"
echo done
pause

I'm posting this in case if anyone needs it. why would you edit my answer?

0

As answered by @Noam Manos, we can improve the zipping a little more by using alias in .bashrc file:

alias zip='jar -cMf'

and then the command (in bash terminal) would be

zip target.zip dir1 dir2

Note: you should have java and git bash installed and setup in windows for this to work.

kittu
  • 6,662
  • 21
  • 91
  • 185
  • Thanks, but as the question stated: `without the need to install any third-party software`. so if I need to install Java and GitBash, I would just install ZIP. – Roee Gavirel Jan 20 '22 at 08:10
  • I guess, the original question I asked (8 years ago) was when we have several data-center world-wide with physical instances (it was before the cloud), so new software installation would required us to install it manually on ~100 machines which is what I tried to avoid. – Roee Gavirel Jan 20 '22 at 11:34