- Windows: Zip | Unzip – Command Line
- Zip/Unzip From The Command Line In Windows
- PowerShell 5.0 (Windows 10) and greater
- PowerShell 3.0 (Windows 8) and greater
- Работа с 7zip из командной строки
- Распаковать и заархивировать
- Распаковка
- Архивация
- Резервное копирование с помощью 7-Zip
- Полный пример cmd-скрипта для резервного копирования:
- Пример Powershell скрипта для резервного копирования:
- Описание ключей и команд 7z
- Описание основных команд
- Описание ключей
- Примеры
- Исключение файлов и папок
- Резервирование баз 1С
- How to unzip a file using the command line? [closed]
- 10 Answers 10
- Create .zip folder from the command line — (Windows)
- 11 Answers 11
- PowerShell
- Directory
- How can you zip or unzip from the script using ONLY Windows’ built-in capabilities?
- 16 Answers 16
- PowerShell 5.0
Windows: Zip | Unzip – Command Line
In the past it was not possible to create Zip files and Unzip archives in Windows without installing third-party programs like WinZip and 7-Zip.
But now Windows has a built-in capability to Zip files and folders and Unzip archives from the command line using PowerShell.
Starting from Windows 8 with PowerShell 3.0 and .NET Framework 4.5 installed by default, it is possible to use a kind of zip and unzip commands from the command line.
Cool Tip: Download a file using PowerShell! Read more →
Zip/Unzip From The Command Line In Windows
Depending on the version of PowerShell there are different ways to Zip files and folders and Unzip archives in Windows from the command line.
To determine a version of PowerShell on your machine, execute:
PowerShell 5.0 (Windows 10) and greater
Starting from PowerShell 5.0 (Windows 10), it is possible to Zip files and folders and Unzip archives in Windows using Compress-Archive and Expand-Archive PowerShell commands.
Zip a file or a folder from the command line in Windows:
Zip all files in a folder:
Unzip an archive from the command line in Windows:
PowerShell 3.0 (Windows 8) and greater
Starting from PowerShell 3.0 (Windows 8), it is possible to Zip folders and Unzip archives in Windows from the command line using the special methods in PowerShell.
Zip all files in a folder from the command line in Windows:
Unzip an archive from the command line in Windows:
Работа с 7zip из командной строки
Приведенные ниже команды выполняются после перехода в каталог с установленным 7-Zip. Как правило, это:
cd «C:\Program Files\7-Zip»
Распаковать и заархивировать
Распаковка
Синтаксис для распаковки:
* ключ x распаковывает с сохранением каталожной структуры; e — все в одно место.
7z x c:\temp\archive.7z -o»c:\temp\»
* в данном примере мы распакуем файл c:\temp\archive.7z в папку c:\temp
Архивация
Синтаксис для архивирования:
7z a -tzip -mx5 -r0 c:\temp\archive.zip c:\temp
* в данном примере мы создадим zip-архив с уровнем компрессии 5; в архив попадет все содержимое всех каталогов; название для файла c:\temp\archive.zip; запаковываем все содержимое папки c:\temp.
7z a -mx1 c:\temp\archive.7z c:\temp\file1.txt c:\temp\file2.txt c:\temp\file3.txt
* в данном примере мы архивируем файлы c:\temp\file1.txt, c:\temp\file2.txt, c:\temp\file3.txt с низкой компрессией 1; в итоге будет получен архив c:\temp\archive.7z.
Резервное копирование с помощью 7-Zip
Один из самых распространенных примеров использования 7zip из командной строки — резервирование данных.
Для начала переходим в каталог с установленной программой:
cd «C:\Program Files\7-Zip\»
* так как в пути имеется пробел, его необходимо писать в кавычках.
Сама команда выглядит следующим образом:
7z a -tzip -ssw -mx1 -pPassword -r0 C:\Temp\backup.zip C:\Data
* в данном примере мы архивируем содержимое папки C:\Data и сохраняем в виде файла C:\Temp\backup.zip.
* описание ключей смотрите ниже или командой 7z —help.
Полный пример cmd-скрипта для резервного копирования:
set source=»C:\Date»
set destination=»C:\Temp»
set passwd=»Password»
set dd=%DATE:
3,2%
set yyyy=%DATE:
6,4%
set curdate=%dd%-%mm%-%yyyy%
«C:\Program Files\7-Zip\7z.exe» a -tzip -ssw -mx1 -p%passwd% -r0 %destination%\backup_%curdate%.zip %source%
* данный скрипт заархивирует содержимое каталога C:\Data в файл C:\Temp\backup_ .zip. Полученный архив будет защищен паролем Password.
* содержимое необходимо сохранить в файле с расширением .cmd или .bat.
Пример Powershell скрипта для резервного копирования:
$source = «C:\Date»
$destination = «C:\Temp»
$passwd = «Password»
$curdate = (Get-Date -UFormat «%d-%m-%Y»)
& «C:\Program Files\7-Zip\7z.exe» a -tzip -ssw -mx1 -p$passwd -r0 $destination\backup_$curdate.zip $source
* данный скрипт также заархивирует содержимое каталога C:\Data в файл C:\Temp\backup_ .zip. Полученный архив будет защищен паролем Password.
* содержимое необходимо сохранить в файле с расширением .ps1.
Описание ключей и команд 7z
В синтаксисе работы с 7zip идут команды и ключи.
Описание основных команд
Команда | Описание |
---|---|
a | Добавление файлов в архив. Если архивного файла не существует, создает его. |
d | Удаление файла из архива |
e | Извлечение файлов из архива. Все файлы оказываются в одной папке. |
l | Вывод содержимого архива. |
rn | Переименовывание файла внутри архива. |
u | Обновление файлов в архиве. Если файла нет, создает новый. |
x | Извлечение файлов из архива. Пути сохраняются. |
Описание ключей
Ключ | Описание |
---|---|
-t | Тип архива. По умолчанию создаются файлы в формате 7z. Примеры, -tzip, -tgz |
-ssw | Включить файл в архив, даже если он в данный момент используется. Для резервного копирования очень полезный ключ. |
-mx | Уровень компрессии. 0 — без компрессии (быстро), 9 — самая большая компрессия (медленно). Например, -mx4 |
-p | Пароль для архива. Например, -pStrong2!3paSsword |
-o | Задает директорию, например, в которую будут распакованы файлы. |
-r | Рекурсивное архивирование для папок. Задается числом от 0 (все каталоги) до количества уровней каталогов, которые нужно включить в архив. |
Другие полезные ключи:
Ключ | Описание |
---|---|
-sdel | Удалить файлы после создания архива. |
-sfx | Создание самораспаковывающегося sfx-архива. |
-y | Утвердительно ответить на все вопросы, которые может запросить система. |
-x | Исключить файлы или папки из архива. |
-v | Позволяет разбить архив на фрагменты. Если указать -v1g, то архив будет разбит на части по 1 Гб. |
-mmt | Количество потоков процессора, которые можно задействовать для работы программы. -mmt=4 укажет работать в четыре потока. |
Полный список ключей и команд можно получить командой 7z —help.
Примеры
Исключение файлов и папок
Отдельно стоит рассказать про возможность исключения. Есть два варианта ее применения.
Первый — создать список исключений в отдельном файле.
Пример команды 7z:
7z.exe a -tzip -ssw -mx9 -r0 -x@exclus.txt C:\Temp\backup.zip C:\Data
* где exclus.txt — файл с исключениями.
Пример файла с исключениями:
* в данном примере мы исключаем каталог с именем test и все файлы с расширением tmp.
Второй — указать исключение в команде.
7z.exe a -tzip -ssw -mx9 -r0 -xr!Шаблон* C:\Temp\backup.zip C:\Data
Резервирование баз 1С
Данные базы 1С находятся в файлах с расширением .1CD. Для их резервирования используем команду:
How to unzip a file using the command line? [closed]
Want to improve this question? Update the question so it’s on-topic for Stack Overflow.
Closed 8 years ago .
Which commands can be used via the command line to unzip a file?
Preferably something built into Windows or open source/free tools.
10 Answers 10
If you already have Java Development Kit on your PC and the bin directory is in your path (in most cases), you can use the command line:
or if not in your path:
Complete set of options for the jar tool available here.
7-Zip, it’s open source, free and supports a wide range of formats.
Firstly, write an unzip utility using vbscript to trigger the native unzip functionality in Windows. Then pipe out the script from within your batch file and then call it. Then it’s as good as stand alone. I’ve done it in the past for numerous tasks. This way it does not require need of third party applications, just the one batch file that does everything.
Use it like this:
As other have alluded, 7-zip is great.
Note: I am going to zip and then unzip a file. Unzip is at the bottom.
7-Zip Command Line Version
You can put the following into a .bat file
I’ve shown a few options.
-r is recursive. Usually what you want with zip functionality.
a is for «archive». That’s the name of the output zip file.
-p is for a password (optional)
-w is a the source directory. This will nest your files correctly in the zip file, without extra folder information.
-mem is the encryption strength.
There are others. But the above will get you running.
NOTE: Adding a password will make the zip file unfriendly when it comes to viewing the file through Windows Explorer. The client may need their own copy of 7-zip (or winzip or other) to view the contents of the file.
EDIT. (just extra stuff).
There is a «command line» version which is probably better suited for this: http://www.7-zip.org/download.html
So the zip command would be (with the command line version of the 7 zip tool).
Now the unzip portion: (to unzip the file you just created)
As an alternative to the «e» argument, there is a x argument.
Create .zip folder from the command line — (Windows)
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.
11 Answers 11
Windows 10 includes tar.exe :
If you have older Windows, you can still download it:
PowerShell
Directory
For both tools, you can use a file or directory for the input.
Imagine that you want to compress the same folder that you are on Command Prompt WITHOUT opening a powershell window:
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-
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 —
It is possible to run PowerShell script from BAT. Bat file receive path to dir to be zipped and zip file name as parameters.
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.
How can you zip or unzip from the script using ONLY Windows’ built-in capabilities?
In Windows you can zip some files by
right click → Send to → Compressed (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?
16 Answers 16
Back in 2013, that was not possible. Microsoft didn’t provide any executable for this.
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
To expand upon Steven Penny’s PowerShell solution, you can incorporate it into a batch file by calling powershell.exe like this:
As Ivan Shilo said, this won’t work with PowerShell 2, it requires PowerShell 3 or greater and .NET Framework 4.
If you have Java installed, you can compress to a ZIP archive using the jar command:
c = Creates a new archive file.
M = Specifies that a manifest file should not be added to the archive.
f = Indicates target file name.
PowerShell 5.0
Create result.zip from the entire Test folder:
Extract the content of result.zip in the specified Test folder:
It isn’t exactly a ZIP, but the only way to compress a file using Windows tools is:
Advanced example (from ss64.com):
Using 7-Zip:
Zip: you have a folder foo , and want to zip it to myzip.zip
Unzip: you want to unzip it ( myzip.zip ) to current directory ( ./ )
100 machines in production which don’t have 7zip on them. To install that I would have to get the DevOps install it on all those machines and on all new machines that will be added to the clusters. I would rather avoid it. – Roee Gavirel May 9 ’16 at 5:27
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.
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.