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...
Super User is a question and answer site for computer enthusiasts and power users. It only takes a minute to sign up.
Sign up to join this communityWindows 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 has Compress-Archive:
# example 1
Compress-Archive in.txt out.zip
# example 2
Expand-Archive out.zip
For both tools, you can use a file or directory for the input.
[IO.Compression.ZipFile]::CreateFromDirectory
did.
Apr 2, 2021 at 17:22
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!
tar -c -a
does create ZIP files, given that the -z
option is not provided additionally…
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
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!
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
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
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
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
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
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>
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
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.
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
compress.exe
.