- Command line zipping windows
- 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С
Command line zipping windows
a command line
multi function tool.
free external tools,
zero install effort,
usb stick compliant:
How to get zip and unzip on the windows command line for quick creation and extraction of zip compressed files. |
Download the free Windows executables: (for Linux, see below)
- to extract zip files on the command line, download unzip.exe here.
this file is a copy of the original Info-ZIP unzip.exe version 5.52, provided for free under the Info-ZIP license. Alternatively, you may download it via the original Info-ZIP website.
How to use unzip? Read the examples below.
to create zip files on the command line, download zip.exe here.
this file is a copy of the original Info-ZIP zip.exe version 2.32, provided for free under the Info-ZIP license. Alternatively, you may download it via the original Info-ZIP website.
How to use zip? Read the examples below.
- include or exclude sub folders or filenames
- zip only files changed today, or in the last 3 days
- with full UTF-8 unicode filename support
download Swiss File Knife here. Then type sfk zip or sfk unzip and read the examples.
this tool is created and maintained only by this website, www.stahlworks.com, and not associated with Info-ZIP. Swiss File Knife Base is Free Open Source, BSD licensed. (more)
to extract .tar.gz and .tar.bz2 files under windows, download:
gzip.exe | 1.3.12 | a copy from http://gnuwin32.sourceforge.net/ |
bzip2.exe | 1.0.5 | a copy from http://www.bzip.org/ |
tar.exe | a copy from http://sourceforge.net/projects/unxutils/ |
All binaries can be used instantly, requiring no further DLL’s.
Some command examples:
gzip -d foo.tar.gz | uncompresses foo.tar.gz, replacing it by foo.tar |
bzip2 -d foo.tar.bz2 | uncompresses foo.tar.bz2, replacing it by foo.tar |
tar tvf foo.tar | lists the contents of foo.tar |
tar xvf foo.tar | extracts the contents of foo.tar |
- Zip and Unzip for newer (lib6 based) distributions: unzip 5.51, zip 2.3
- Zip and Unzip for older (lib5 based) distributions: unzip 5.50, zip 2.3
These files are copies from the Info-Zip download locations listed above,
provided under the Info-ZIP license.
These files are provided for free under the BSD license.
Further zip tools of possible interest:
Although not discussed here, it should be mentioned that the original Info-ZIP homepage provides further tools, e.g. for the creation of self-extracting zips, gzip and zipsplit, and of course zip/unzip binaries for many other operating systems.
Example for searching through zip file contents:
searches all .java files within eclipse.zip for lines with the words «public» AND «class».
Note that zzfind can also search files in a zip within a zip (nested zips).
How to list nested zip file contents (zips or jars within zips):
For example, if you download the Eclipse SDK and type you get a listing of less than 2000 files, listing also .jar file names. But how can you also list what is inside the .jar files, without the need to extract everything first?
Download Swiss File Knife Base, then type: This will produce a listing of all files, no matter how deeply nested — in total nearly 70000 lines that can be very long, for example:
eclipse-SDK-3.3.2-win32.zip\\eclipse\plugins \org.eclipse.ant.core_3.1.200.v20070522.jar\\lib \antsupportlib.jar\\org\eclipse\ant \internal\core\ant\EclipseAntMain.class |
The above is the text of a single line (filename), split into 4 lines here for better reading.
As you can see, there is a .class file in a .jar within another .jar within the .zip.
Limitations: SFK may not be able to process very large zip files, zip files with an unusual compression method, or 64 bit zip files. Type sfk help xe to list all limitations.
How to list the contents of all .zip files in all subdirectories:
In the example above, we listed the content of a single zip file. But sfk can also list the contents of all .zip, .jar, .ear, .war and .aar files in a directory tree. type: and get the most comprehensive listing of all files, all .zip (.jar etc) file contents
and even zip contents embedded within other zips.
Flexible file selection for zipping, using sfk:
If you don’t want to zip all files of a directory tree, but for example
- files that changed today, or since a date
- files with a specific file extension
- all files except those in subdirectories \save\ and \tmp\
- files that are different compared to another directory
then you have to prepare a file list with the swiss file knife, and send this to the zip tool through zip’s option -@ (read file list from standard input).
example: zipping files changed today
four files were changed today, so only those are packed into update.zip. |
example: including/excluding by filename
only files with extension .txt are collected from the docs directory, excluding files
the example uses sfk for windows syntax. linux users have to type «:» instead of «!». |
example: comparing directories
we have two directory trees, «docs» and «docs-old». the latter one is a copy of docs, made some days ago. meanwhile, there have been changes in «docs». but what changes?
this command only lists what has changed so far:
|
so let’s collect all these differences into a .zip. notice that zip would be irritated by the [add] and [dif] prefixes in each line, therefore we have to add sfk option -pure:
now let’s send this to zip:
NTFS and ZIP — execution prevention problem:
i experienced one small problem when using the command-line (un)zip together with NTFS file systems; in short terms, after unzipping «.msi» files, I was unable to install software from these files. windows complained that access to the files was not possible or denied (due to some «execution prevention» mechanism introducted with XP SP2). this was probably because i zipped those files from a FAT partition (maybe even with an older zip tool) and then unzipped them on NTFS. the solution was to copy the files to a partition with FAT(32) file system, e.g. an USB stick, and then to run the installer from there.
NTFS and ZIP — filetime jumps:
another issue concerns filetimes, especially when zipping/unzipping accross FAT and NTFS partitions. in short terms, if you zip files from a FAT partition, then unpack this .zip on an NTFS partition, you always have to expect that the filetimes may be changed globally by a few hours. This is not at all a bug in the zip tool — it’s due to the way that NTFS manages filetimes internally. in case you’re irritated by this, try the following: 1) remember the filetimes in some directory on an NTFS partition. 2) change the date of your system from summer to winter time, or vice versa 3) have a look again at the filetimes and be shocked: all file times have jumped by one hour! so this is not a zip-specific problem, but it may show up when you compare times listed in a .zip file with those of the files actually created.
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. Для их резервирования используем команду: