170

Is it possible to create a .zip file from a folder in the command line, I don't want to use any third party executable.

I was thinking something like 'send to compressed folder' but I don't know how to do it...

2
  • 2
    There's a tool in the Windows resource kit called compress.exe.
    – ho1
    Oct 20, 2010 at 7:56
  • 4
    Here's a link to a ServerFault question that discusses just this: serverfault.com/questions/39071/…
    – ho1
    Oct 20, 2010 at 7:57

12 Answers 12

164

Tar

Windows 10 includes tar.exe:

# example 1
tar.exe -a -c -f out.zip in.txt
# example 2
tar.exe -x -f out.zip

If you have older Windows, you can still download from libarchive/libarchive.

PowerShell

PowerShell has Compress-Archive:

# example 1
Compress-Archive in.txt out.zip
# example 2
Expand-Archive out.zip

Directory

For both tools, you can use a file or directory for the input.

9
  • 2
    The second option didn't work for me on 17G dump file. But [IO.Compression.ZipFile]::CreateFromDirectory did. Apr 2, 2021 at 17:22
  • 2
    Note to newbies like me - with tar.exe, Windows can't natively open it like a usual zip file (stackoverflow.com/questions/70038020/…). Free apps still can though,
    – EvilDr
    Nov 19, 2021 at 18:34
  • 8
    tar doesn't work like you think it does though. it creates a tar file of all the files you specify then zips that tar file. so you end up with a zip file that contains a single file, which is a tar file that contains all your files. so you're going to have compatibility issues with programs that expect a zip file that directly contains your files.
    – Jason C
    Nov 28, 2021 at 3:41
  • 5
    tar has no -a option (it just seems to be ignored), it's tar.exe -c -f out.zip in.txt (example 1)! And tar doesn't create .zip archives, it creates .tar files, or, if the -z switch is provided, .tar.gz files!
    – aschipfl
    Feb 10, 2022 at 11:44
  • 4
    @TrayMan, you're absolutely right as I just found out! tar -c -a does create ZIP files, given that the -z option is not provided additionally…
    – aschipfl
    Jun 1, 2022 at 11:07
60

Imagine that you want to compress the same folder that you are on Command Prompt WITHOUT opening a powershell window:

powershell Compress-Archive . publish.zip
1
  • 1
    That wasn't what I set out to do, but it will work for me now. That's a handy trick to know. Apr 4, 2019 at 4:48
8

I don't think there is a command line for ZIP files built in to Windows (Other than compress in Server 2003 Resource Kit). You'd have to use a third party. Everybody loves 7zip!

8

I've combined this script from several different sources to suit my needs better. Copy and paste the script into a file with the extension ".vbs". The script was originally made for Windows XP, but it also works in Windows 7 x64 Ultimate - no guarantee's if Windows will keep around the various Shell objects this uses.

Usage: in the run box or command line put-

"C:\zipper.vbs" "C:\folderToZip\" "C:\mynewzip.zip"

Path to script, source folder, zip file to make (include .zip at the end).

It won't copy empty folders so be careful.

Here is the vbs code ---

Set Args = Wscript.Arguments
source = Args(0)
target = Args(1)

' make sure source folder has \ at end
If Right(source, 1) <> "\" Then
    source = source & "\"
End If

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set zip = objFSO.OpenTextFile(target, 2, vbtrue)
' this is the header to designate a file as a zip
zip.Write "PK" & Chr(5) & Chr(6) & String( 18, Chr(0) )
zip.Close
Set zip = nothing

wscript.sleep 500

Set objApp = CreateObject( "Shell.Application" )
intSkipped = 0

' Loop over items within folder and use CopyHere to put them into the zip folder
For Each objItem in objApp.NameSpace( source ).Items
    If objItem.IsFolder Then
        Set objFolder = objFSO.GetFolder( objItem.Path )
        ' if this folder is empty, then skip it as it can't compress empty folders
        If objFolder.Files.Count + objFolder.SubFolders.Count = 0 Then
            intSkipped = intSkipped + 1
        Else
            objApp.NameSpace( target ).CopyHere objItem
        End If
    Else
        objApp.NameSpace( target ).CopyHere objItem
    End If
Next

intSrcItems = objApp.NameSpace( source ).Items.Count
wscript.sleep 250

' delay until at least items at the top level are available
Do Until objApp.NameSpace( target ).Items.Count + intSkipped = intSrcItems
    wscript.sleep 200
Loop

'cleanup
Set objItem = nothing
Set objFolder = nothing
Set objApp = nothing
Set objFSO = nothing
3
  • 1
    Looks promising, but I got an "Object required: 'objApp.NameSpace(...)' error on line 16
    – pihentagy
    Nov 20, 2012 at 8:55
  • I have the same problem. The above code doesn't work, or needs some extra stuff in the system the poster forgot to mention.
    – MBender
    Feb 1, 2013 at 11:13
  • It uses WScript (vbs environment) and several Shell objects. All were installed by default in Windows XP (business?) and Win 7 Ultimate x64. Perhaps they are longer there for Win8?
    – WSkid
    Feb 1, 2013 at 18:25
3

It is possible to run PowerShell script from BAT. Bat file receive path to dir to be zipped and zip file name as parameters.

@echo off
setlocal

rem First parameter - path to dir to be zipped
rem Second parameter- zip file name
set sourceDir=%1
set zipFile=%2

rem Create PowerShell script
echo Write-Output 'Custom PowerShell profile in effect!'    > %~dp0TempZipScript.ps1
echo Add-Type -A System.IO.Compression.FileSystem           >> %~dp0TempZipScript.ps1
echo [IO.Compression.ZipFile]::CreateFromDirectory('%sourceDir%','%~dp0%zipFile%') >> %~dp0TempZipScript.ps1

rem Execute script with flag "-ExecutionPolicy Bypass" to get around ExecutionPolicy
PowerShell.exe -ExecutionPolicy Bypass -Command "& '%~dp0TempZipScript.ps1'"
del %~dp0TempZipScript.ps1
endlocal
4
  • 1
    But what would be the advantage to this approach? Why not just write the PowerShell script to a fixed file and let it accept parameters?
    – Seth
    Nov 30, 2016 at 14:01
  • I tried all the other solutions. this is the only fail-safe solution that works perfectly. The most important advantage is use of powershell's native commands and no need to create the old-tech VBScript.
    – Hossein
    Apr 8, 2019 at 10:11
  • This worked for me on an old corporate windows7 laptop in 2019.
    – simbo1905
    Aug 21, 2019 at 7:26
  • 1
    Can be run direct from CMD, no need to create .ps1 files
    – Zimba
    Mar 17, 2020 at 7:06
3

To compress file from CMD:

compact /c /exe lzx input.txt

(works on NTFS Volumes) File size after compression still displays same on CLI dir or GUI File Properties, but disk space occupied is (6-8 times) less. Binary compressed files won't make much difference.

For ZIP file format from PKWare, compression rate is about 4 times higher than compact (from testing on Win 10) and incorporates a range of compression algorithms such as Deflate, BZip, LZW, LZMA, LZ77, PPMd, etc

These technologies are newer than the days of DOS & CMD, and but still can be accessed via newer CLI tools like Powershell, JScript, VBScript, etc.

For powershell from Win CMD:

powershell "Compress-Archive input.txt output.zip"

or tar in Windows 10:

Usage:
  List:    tar -tf <archive-filename>
  Extract: tar -xf <archive-filename>
  Create:  tar -cf <archive-filename> [filenames...]
  Help:    tar --help
2

This is an old question, but it's relevance is still current.

Windows of course has it's own compression algorithm built in for using zip files, but, it really performs poorly when compared to the 7zip open source product found here http://www.7-zip.org/

Others have already discussed various methods for using the built in windows functions, my solution requires installing the additional software.

7Zip supports a wide range of files, including ZIP, RAR, CAB and ISO and it's own 7z format.

You can view the command line help:

"C:\Program Files\7-Zip\7z.exe" --help

to perform a simple add to zip archive:

"C:\Program Files\7-Zip\7z.exe" a filename.zip c:\path 
1

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

Can you zip a file from the command prompt using ONLY Windows' built-in capability to zip files?

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.

Does Windows 7 have unzip at the command line installed by default?

https://stackoverflow.com/questions/1021557/how-to-unzip-a-file-using-the-command-line

1
  • 4
    You should include the instructions in your answer. If the links go stale, your answer will be worthless...
    – MoonSire
    Nov 15, 2013 at 6:50
1

I will post something related to WSkids answer as sadly i cannot use the comment function.

Using the CopyHere() method in VBS introduces several issues. One of these issues is that the method returns immediately while the copy process starts in background whereas multiple CopyHere() calls will interfere each other and the ZIP won't be created correctly. A wait loop is needed here to fix that. My wait loop is based on an answer to a similar issue posted here.

Here is an updated version which fixes the "Object required" error reported by pihentagy. It's a timing issue as the newly created ZIP file is included in the Items collection when the script is executed on fast machines.

set Args = WScript.Arguments
source = Args(0)
' remove trailing slashes as we add slashes when needed later
while Right(source, 1) = "\"
    source = Mid(source, 1, Len(source) - 1)
wend

target = Args(1)

' create empty ZIP file
set fso = CreateObject("Scripting.FileSystemObject")
set zip = fso.OpenTextFile(target, 2, vbtrue)
' write ZIP header, this ensures that Windows recognizes the file as "ZIP Folder"
zip.Write "PK" & Chr(5) & Chr(6) & String(18, Chr(0))
zip.Close
set zip = nothing
set fso = nothing

' copy files to ZIP file
set app = CreateObject("Shell.Application")

set sourceFolderObj = app.NameSpace(source)
set targetFolderObj = app.NameSpace(target)

for each item in sourceFolderObj.Items
  itemPath = source & "\" & item.Name
  
  copyItem = false
  
  ' ZIP file is included in Items collection and is recognized as folder, thus skip it to avoid script errors
  if itemPath <> target then
    if item.IsFolder then
      if item.GetFolder.Items().Count = 0 then
        ' folder is empty, skip it as empty folders can't be compressed
      else
        copyItem = true
      end if
    else
      copyItem = true
    end if
  end if
  
  if copyItem then
    targetFolderObj.CopyHere item
    
    ' wait until the file appears in the ZIP file, 
    ' this is needed because CopyHere() returns immediately after starting an asynchronous copy process 
    ' (starting multiple asynchronous copy will not work as it causes error messages, an invalid ZIP file, ...)
    while (targetFolderObj.ParseName(item.Name) is nothing)
      WScript.Sleep 1
    wend
  end If
next

set targetFolderObj = nothing
set sourceFolderObj = nothing
set app = nothing
1
  • 1
    Nice work; I've been in a situation a few times where I'm not allowed to run non-whitelisted exes, I'll keep this in my toolbox, with a small modification of an argument to overwrite or add to existing file. Feb 27, 2020 at 21:35
1

Here is another idea, from 4 different sources; not my ideas, but I compiled them to make it work for me

<!-- : Begin batch script
@each off

set sourceFolder="c:\test"
set destZip="%userprofile%\desktop\example.zip"

cscript //nologo "%~f0?.wsf" //job:exewsh %sourceFolder% %destZip%

exit /b
GOTO:EOF
----- Begin wsf script --->
<package><job id="exewsh"><script language="VBScript">
'Get command-line arguments.
Set objArgs = WScript.Arguments
InputFolder = objArgs(0)
ZipFile = objArgs(1)

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

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

'Required!
wScript.Sleep 2000
</script></job>
</package>
2
  • 4
    Welcome to Super User! This is obviously a complicated script. Could you explain what it does, and how to use it?
    – jpaugh
    Jan 18, 2018 at 23:27
  • it's a hybrid batch-vbs script. Save that as *.bat and run like a normal *.bat file
    – phuclv
    Aug 23, 2023 at 1:21
0

See my answer on How to compress (/ zip ) and uncompress (/ unzip ) files and folders with batch file without using any external tools?

with a few given solutions that should work on almost every windows machine.

4
  • 2
    Please expand your answer - it relies much too heavily on a link that may die anytime.
    – studiohack
    May 18, 2015 at 21:58
  • 2
    @studiohack this is a link to Stackoverflow. If it dies - they die together
    – jitbit
    Sep 14, 2021 at 9:23
  • 1
    @jitbit I see your point - however questions/answers get deleted for all kinds of reasons, independent of the site.
    – studiohack
    Sep 14, 2021 at 17:24
  • @studiohack - I'll update the answer...
    – npocmaka
    Sep 15, 2021 at 5:41
0

This is on Windows Server 2019 Datacenter. In the end, the undocumented "-a" option suggested by @Zombo is required to create ZIP compatible files.

> tar --help

tar(bsdtar): manipulate archive files

First option must be a mode specifier:
  -c Create  -r Add/Replace  -t List  -u Update  -x Extract
Common Options:
  -b #  Use # 512-byte records per I/O block
  -f <filename>  Location of archive (default \\.\tape0)
  -v    Verbose
  -w    Interactive
Create: tar -c [options] [<file> | <dir> | @<archive> | -C <dir> ]
  <file>, <dir>  add these items to archive
  -z, -j, -J, --lzma  Compress archive with gzip/bzip2/xz/lzma
  --format {ustar|pax|cpio|shar}  Select archive format
  --exclude <pattern>  Skip files that match pattern
  -C <dir>  Change to <dir> before processing remaining files
  @<archive>  Add entries from <archive> to output
List: tar -t [options] [<patterns>]
  <patterns>  If specified, list only entries that match
Extract: tar -x [options] [<patterns>]
  <patterns>  If specified, extract only entries that match
  -k    Keep (don't overwrite) existing files
  -m    Don't restore modification times
  -O    Write entries to stdout, don't restore to disk
  -p    Restore permissions (including ACLs, owner, file flags)
bsdtar 3.5.2 - libarchive 3.5.2 zlib/1.2.5.f-ipp

Try the documented compression and format options

>tar -c -z --format ustar -f Test1.z.ustar.zip  tar_filelist.txt              creates a file that Windows Explorer can't open.

>tar -c -j --format ustar -f Test2.j.ustar.zip  tar_filelist.txt              creates a 0 byte file that Windows Explorer CAN open.  Shows as empty.
tar: Can't launch external program: bzip2

>tar -c -J --format ustar -f Test3.J.ustar.zip  tar_filelist.txt              errors out.  does nothing.
tar: Unsupported compression option --xz

>tar -c --lzma --format ustar -f Test4.lzma.ustar.zip  tar_filelist.txt       errors out.  does nothing.
tar: Unsupported compression option --lzma

>tar -c -z --format pax -f Test5.z.pax.zip  tar_filelist.txt                  creates a file that Windows Explorer can't open.

>tar -c -j --format pax -f Test6.j.pax.zip  tar_filelist.txt                  creates a 0 byte file that Windows Explorer CAN open.  Shows as empty.
tar: Can't launch external program: bzip2

>tar -c -J --format pax -f Test7.J.pax.zip  tar_filelist.txt                  errors out.  does nothing.
tar: Unsupported compression option --xz

>tar -c --lzma --format pax -f Test8.lzma.pax.zip  tar_filelist.txt           errors out.  does nothing.
tar: Unsupported compression option --lzma

>tar -c -z --format cpio -f Test9.z.cpio.zip  tar_filelist.txt                creates a file that Windows Explorer can't open.

>tar -c -j --format cpio -f Test10.j.cpio.zip  tar_filelist.txt               creates a 0 byte file that Windows Explorer CAN open.  Shows as empty.
tar: Can't launch external program: bzip2

>tar -c -J --format cpio -f Test11.J.cpio.zip  tar_filelist.txt               errors out.  does nothing.
tar: Unsupported compression option --xz

>tar -c --lzma --format cpio -f Test12.lzma.cpio.zip  tar_filelist.txt        errors out.  does nothing.
tar: Unsupported compression option --lzma

>tar -c -z --format shar -f Test13.z.shar.zip  tar_filelist.txt               creates a file that Windows Explorer can't open.

>tar -c -j --format shar -f Test14.j.shar.zip  tar_filelist.txt               creates a 0 byte file that Windows Explorer CAN open.  Shows as empty.
tar: Can't launch external program: bzip2

>tar -c -J --format shar -f Test15.J.shar.zip  tar_filelist.txt               errors out.  does nothing.
tar: Unsupported compression option --xz

>tar -c --lzma --format shar -f Test16.lzma.shar.zip  tar_filelist.txt        errors out.  does nothing.
tar: Unsupported compression option --lzma


## Results of the commands above
## The "z" option creates a file that Windows Explorer can't open.
## The "j" option creates a 0 byte file that Windows Explorer CAN open.  Shows as empty.

08/22/2023  07:30 PM               107 Test1.z.ustar.zip
08/22/2023  07:32 PM                 0 Test2.j.ustar.zip

08/22/2023  07:34 PM               211 Test5.z.pax.zip
08/22/2023  07:36 PM                 0 Test6.j.pax.zip

08/22/2023  07:37 PM               102 Test9.z.cpio.zip
08/22/2023  07:38 PM                 0 Test10.j.cpio.zip

08/22/2023  07:39 PM               128 Test13.z.shar.zip
08/22/2023  07:39 PM                 0 Test14.j.shar.zip

You must log in to answer this question.