- Работа с 7zip из командной строки
- Распаковать и заархивировать
- Распаковка
- Архивация
- Резервное копирование с помощью 7-Zip
- Полный пример cmd-скрипта для резервного копирования:
- Пример Powershell скрипта для резервного копирования:
- Описание ключей и команд 7z
- Описание основных команд
- Описание ключей
- Примеры
- Исключение файлов и папок
- Резервирование баз 1С
- Windows: Zip/Unzip из Командной Строка
- Zip/Unzip Из Командной Строки В Windows
- PowerShell 5.0 (Windows 10) и выше
- PowerShell 3.0 (Windows 8) и выше
- Extract a certain file from an archive with 7-Zip from the command line
- 5 Answers 5
- e (Extract) command
- Examples
- Notes
- How to unzip a file using the command line? [closed]
- 10 Answers 10
Работа с 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. Для их резервирования используем команду:
Windows: Zip/Unzip из Командной Строка
В прошлом было невозможно создавать и распаковывать zip-архивы в Windows без установки сторонних программ, таких как WinZip и 7-Zip.
Но теперь Windows имеет встроенную возможность архивирования файлов и папок и распаковки zip-архивов из командной строки с помощью PowerShell.
Начиная с Windows 8 с PowerShell 3.0 и .NET Framework 4.5, установленных по умолчанию, из командной строки стало возможным выполнять своего рода команды zip и unzip .
Дельный Совет: Скачать файл с помощью PowerShell! Читать далее →
Zip/Unzip Из Командной Строки В Windows
В зависимости от версии PowerShell существуют различные способы создания и распаковки zip-архивов из командной строки в Windows.
Чтобы узнать версию PowerShell на вашей машине, выполните следующую команду:
PowerShell 5.0 (Windows 10) и выше
Начианя с PowerShell 5.0 (Windows 10), стало возможным создавать и распаковывать zip-архивы в Windows с помощью команд Compress-Archive and Expand-Archive в PowerShell.
Сжать файл или папку из командной строки в Windows:
Заархивировать все файлы в папке:
Распаковать архив из командной строки в Windows:
PowerShell 3.0 (Windows 8) и выше
Начиная с PowerShell 3.0 (Windows 8), стало возможным создавать и распаковывать zip-архивы в Windows с помощью определенных методов в PowerShell.
Сжать все файлы в папке из командной строки в Windows:
Распаковать архив из командной строки в Windows:
Extract a certain file from an archive with 7-Zip from the command line
If I have an archive, for example, some.zip that contains one or more files, how can I extract only one file (I know the name of the file) with 7-Zip from the command line in Windows?
5 Answers 5
You just add the filename at the end.
As a follow-up to surfasb’s answer, add a -r flag at the end to recurse:
Multiple filters support:
Multiple filters command line:
PS: I use 7za.exe instead of 7z.exe. This is the actual command I use in my script:
If you look at the man page for 7z you will find that the following command can be used to extract a file from a 7z archive (though the usage of path is missing from the man page):
Alternatively you could use e .
The command line version users guide seems to have more information on the actual usage.
Note that 7z has the following syntax (observe the spaces and quotes surrounding the «-oMy Folder» option to set the output folder name, took me hours to figure out, as I originally did this – the wrong way: * -o «My Folder» *):
I found that on zsh command line, with 7-zip 16.06, that I had to put double-quotes around the wildcard filter argument. For example, this did not find any PDF files to extract:
but quoting the wildcard filter did find and extract the PDF file that was in a subdirectory of the zip archive, like this:
e (Extract) command
Extracts files from an archive to the current directory or to the output directory. The output directory can be specified by -o (Set Output Directory) switch.
This command copies all extracted files to one directory. If you want extract files with full paths, you must use x (Extract with full paths) command.
7-Zip will prompt the user before overwriting existing files unless the user specifies the -y (Assume Yes on all queries) switch. If the user gives a no answer, 7-Zip will prompt for the file to be extracted to a new filename. Then a no answer skips that file; or, yes prompts for new filename.
7-Zip accepts the following responses:
Answer | Abbr. | Action |
---|---|---|
Yes | y | |
No | n | |
Always | a | Assume YES for ALL subsequent queries of the same class |
Skip | s | Assume NO for ALL subsequent queries of the same class |
Quit | q | Quit the program |
Abbreviated responses are allowed.
Examples
extracts all files from archive archive.zip to the current directory.
extracts all *.cpp files from archive archive.zip to c:\soft folder.
Notes
7-Zip doesn’t use the system wildcard parser. 7-Zip doesn’t follow the archaic rule by which *.* means any file. 7-Zip treats *.* as matching the name of any file that has an extension. To process all files, you must use a * wildcard.
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.