69

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
    There's a tool in the Windows resource kit called compress.exe. – ho1 Oct 20 '10 at 7:56
  • 3
    Here's a link to a ServerFault question that discusses just this: serverfault.com/questions/39071/… – ho1 Oct 20 '10 at 7:57

11 Answers 11

44

Starting with PowerShell 5 (February 2016), you can use "Compress-Archive":

Compress-Archive -Path input.txt -DestinationPath output.zip

Or:

Compress-Archive input.txt output.zip

input.txt here could also be a directory

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.archive/compress-archive?view=powershell-5.1

|improve this answer|||||
  • 1
    from Win CMD: powershell "Compress-Archive input.txt output.zip" – Zimba Mar 17 at 7:16
8

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
|improve this answer|||||
  • That wasn't what I set out to do, but it will work for me now. That's a handy trick to know. – bballdave025 Apr 4 '19 at 4:48
7

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!

|improve this answer|||||
7

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
|improve this answer|||||
  • 1
    Looks promising, but I got an "Object required: 'objApp.NameSpace(...)' error on line 16 – pihentagy Nov 20 '12 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. – Shaamaan Feb 1 '13 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 '13 at 18:25
2

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
|improve this answer|||||
  • 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 '16 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. – desmati Apr 8 '19 at 10:11
  • This worked for me on an old corporate windows7 laptop in 2019. – simbo1905 Aug 21 '19 at 7:26
  • Can be run direct from CMD, no need to create .ps1 files – Zimba Mar 17 at 7:06
2

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>
|improve this answer|||||
  • 3
    Welcome to Super User! This is obviously a complicated script. Could you explain what it does, and how to use it? – jpaugh Jan 18 '18 at 23:27
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

|improve this answer|||||
  • 3
    You should include the instructions in your answer. If the links go stale, your answer will be worthless... – MoonSire Nov 15 '13 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
|improve this answer|||||
  • 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. – SilverbackNet Feb 27 at 21:35
1

Here'a my attempt to summarize built-in capabilities windows for compression and uncompression - https://stackoverflow.com/questions/28043589/how-can-i-compres-zip-and-uncopress-unzip-files-and-folders-with-batch-f

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

|improve this answer|||||
  • Please expand your answer - it relies much too heavily on a link that may die anytime. – studiohack May 18 '15 at 21:58
1

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

|improve this answer|||||
0

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"

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy