Comprehensive Tutorial on Zipping in Windows Command Line 📦
In today’s fast-paced digital world, managing your files efficiently is a must. Whether you need to compress a single file, multiple files, or an entire directory, using the Windows command line can be a powerful way to get the job done quickly. This guide walks you through how to zip in Windows command line, including zipping files, folders, and directories. We’ll also recommend the popular tool 7-Zip for those who want more advanced features.
1. Using PowerShell’s Compress-Archive Command 🛠️
For Windows 10 and later, PowerShell includes a built-in command called Compress-Archive. This command allows you to zip files and folders without needing third-party software.
a. Zip a Single File
To zip a single file, open PowerShell and run:
Compress-Archive -Path "C:\Path\To\YourFile.txt" -DestinationPath "C:\Path\To\Archive.zip"
This command takes YourFile.txt
and compresses it into Archive.zip
.
b. Zip Multiple Files
To zip multiple files, list them using a comma-separated array:
Compress-Archive -Path "C:\Path\To\File1.txt", "C:\Path\To\File2.txt" -DestinationPath "C:\Path\To\FilesArchive.zip"
c. Zip a Folder or Directory
Compressing an entire folder is just as simple:
Compress-Archive -Path "C:\Path\To\YourFolder" -DestinationPath "C:\Path\To\FolderArchive.zip"
This command zips the entire contents of YourFolder into FolderArchive.zip.
2. Using 7-Zip from the Command Line 🔧
For those who require additional compression options or support for various archive formats, 7-Zip is a top recommendation. 7-Zip is a free, open-source file archiver with high compression ratios and a powerful command-line interface.
a. Installing 7-Zip
- Download 7-Zip from the official website.
- Install it on your system (default installation path is usually
C:\Program Files\7-Zip\7z.exe
).
b. Using 7-Zip to Zip Files and Folders
Open the Command Prompt and navigate to the directory containing the files or folders you wish to zip. Here are some common commands:
- Zip a Single File:
cmd
"C:\Program Files\7-Zip\7z.exe" a -tzip Archive.zip "YourFile.txt"
- Zip Multiple Files:
cmd
"C:\Program Files\7-Zip\7z.exe" a -tzip FilesArchive.zip "File1.txt" "File2.txt"
- Zip an Entire Folder:
cmd
"C:\Program Files\7-Zip\7z.exe" a -tzip FolderArchive.zip "YourFolder\*"
Explanation of the Command Options:
a
: Add files to archive-tzip
: Specify the archive type (ZIP in this case)Archive.zip
: The name of the output archive"YourFolder\*"
: Includes all files within the folder
3. Comparison Table: PowerShell vs. 7-Zip
Feature | PowerShell Compress-Archive | 7-Zip Command Line |
---|---|---|
Ease of Use | ✅ Very Easy | ✅ Easy with more options |
Built-In | ✅ Included in Windows 10+ | ❌ Requires separate installation |
Supported Formats | ❌ ZIP only | ✅ ZIP, 7z, TAR, GZIP, etc. |
Advanced Options | ❌ Limited | ✅ Extensive (encryption, splits, etc.) |
Table Note: The check icons (✅) indicate the strengths of each method, so choose the one that best fits your needs.
4. Best Practices and Tips for Zipping Files
- Always Verify Paths: Ensure that the file or directory paths are correct to avoid errors.
- Use Meaningful Archive Names: This helps in keeping your files organized and easily identifiable.
- Test the Archive: After compression, try extracting the archive to ensure that all files are intact.
- Automate with Scripts: Consider writing batch scripts or PowerShell scripts to automate regular archiving tasks.
Final Thoughts 🎯
Whether you choose the simplicity of PowerShell’s Compress-Archive or the powerful features of 7-Zip, zipping files and folders via the Windows command line is a valuable skill for efficient file management. Experiment with both methods to see which works best for your workflow, and enjoy the flexibility that command line tools bring to your daily tasks.
Happy zipping, and may your archives always be compact and secure! 🚀
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:
PS C:\> $PSVersionTable.PSVersion
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:
PS C:\> Compress-Archive -Path 'C:\input' -DestinationPath 'C:\output.zip'
Zip all files in a folder:
PS C:\> Compress-Archive -Path 'C:\folder\*' -DestinationPath 'C:\output.zip'
Unzip an archive from the command line in Windows:
PS C:\> Expand-Archive -Path 'C:\input.zip' -DestinationPath 'C:\output'
PowerShell 3.0 (Windows
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:
PS C:\> Add-Type -A 'System.IO.Compression.FileSystem'; [IO.Compression.ZipFile]::CreateFromDirectory('C:\folder', 'C:\output.zip')
Unzip an archive from the command line in Windows:
PS C:\> Add-Type -A 'System.IO.Compression.FileSystem'; [IO.Compression.ZipFile]::ExtractToDirectory('C:\input.zip', 'C:\output')
Was it useful? Share this post with the world!
Last Updated :
30 Aug, 2024
One effective technique to handle data without depending on third-party software is to use the Command Prompt (CMD) on Windows to compress and extract files and directories. To use CMD to compress files and directories, you must utilize the integrated 7z command-line tool. If you work with large files on your Windows computer, then you need to know how to extract files and folders using the command prompt on Windows. You can manage your documents using the command prompt in just simple steps.
In this article, we will show you how to use basic command prompt commands to compress or extract files and folders. This method also helps in improving the efficiency of file transfer and also saves disk space. Now, follow the below methods step-by-step to Compress or Extract files and folders using CMD.
How to Compress or Extract files and folders using CMD?
Although it is mainly used for NTFS file compression, Windows comes with an integrated application called Compact that allows you to compress files and folders. On the other hand, Windows 10 and later versions of Windows allow you to use the Compact command to create ZIP files. Here are some straightforward ways to compress and extract files and folders using the Command Prompt on Windows, complete with a step-by-step guide.
Method 1: Using Compact Command
Step 1: To compress files Click ‘Win + R‘, type ‘cmd’ in the open box, and then press Enter.
Step 2: Next, change the directory to the target location using the cd command:
cd C:\Users\YourUsername\Documents
Step 3: After you have navigated to the directory where compression is needed, type the following command to compress a file:
compact /c filename.ext
Replace filename.ext
with the name of the file, you want to compress.
To compress an entire folder and its subfolders:
compact /c /s:directoryname
Replace directoryname
with the name of the folder you want to compress.
Method 2: Creating a Compressed ZIP File Using Compress Command
Step 1: Open Command Prompt as Administrator.
Step 2: Use the Makecab Command:
First, list all files into a directive file:
dir /b /s *.* > list.txt
Step 3: Then compress the files listed in list.txt
:
makecab /f list.txt
How to Extract Files and Folders?
Now, let’s check out two different methods on how to extract any file and folder using the command prompt in no time.
Method 1: Using Expand Command
Step 1: Search for Command Prompt by either clicking on the Start menu or pressing Win + R. Type cmd, and then hit the Enter key.
Step 2: Use Expand Command:
Navigate to the location of your compressed file (.cab), Use the cd
command to navigate:
cd C:\Path\To\Your\File
from there, you can make use of Expand Command.
expand filename.cab -F:* C:\DestinationFolder
Replace filename.cab with the name of your compressed file and C:\DestinationFolder with the path where you want the files to be extracted.
Method 2: Extracting ZIP Files using PowerShell
Step 1: To launch PowerShell, type that in the Start menu.
Step 2: Use the cd command to navigate to the location of the file:
cd C:\Path\To\Your\File
Step 3: Extract the ZIP file:
Expand-Archive -Path "C:\path\to\your\file.zip" -DestinationPath "C:\path\to\extract\to"
Replace "C:\path\to\your\file.zip"
with the path to your ZIP file and "C:\path\to\extract\to"
with the path where you want the files to be extracted.
These methods provide you with basic skills for compression and extraction using Command Prompt and PowerShell for files on Windows.
Conclusion
To put it simply, using the Command Prompt in Windows for file/folder compression or deletion is straightforward and efficient. This strategy is particularly valuable for handling large data sets economically. If you learn just a handful of basic commands like ‘’compact” and ”expand’’, you can reduce volumes of disk space and enhance your file organization. Employing these commands consistently will enhance your expertise and enable you to exploit all the capabilities your Windows system offers.
Also Read
- How to Unzip Files on Windows and Mac?
- How to Compress Files in Linux | Tar Command
- How to compress file in Linux | Compress Command
Sign in to your MUO account
Are you running out of space on your Windows PC? The best thing you can do to free up some space is to compress big files through zipping. There are plenty of third-party tools that can come in handy in this situation.
However, if you prefer to use Command Prompt or Windows PowerShell over anything else, there are commands you can use in these utilities to zip or unzip files. So, let’s check out how to zip or unzip files using Command Prompt and Windows PowerShell.
How to Zip Files Using Command Prompt
You can zip files through Command Prompt using the tar command. It’s a command line tool that helps you to extract files and create archives. However, this command only works in Windows 10 or later.
Here’s how to zip files using Command Prompt:
- Open the Start Menu by pressing the Win key.
- In the search bar, type Command Prompt and Run as administrator from the right pane.
-
In the console, type the following command and press Enter. Replace ‘Place’ with the location of the file.
cd Place
-
Type dir and press Enter. It’ll show the files inside the selected folder.
-
To zip all the files inside the selected folder, type the following command and press Enter. Replace ‘Compressed‘ with the name you want to give your folder where the zip file will be stored. Also, replace ‘FileExt‘ with the extension of the file you’re zipping.
tar -a -c -f Compressed.zip *.FileExt
-
To zip a single file, execute the following command. Again, replace ‘Compressed‘ with the name you want to give your folder where the zip file will be stored, ‘FileExt‘ with your file’s extension, and ‘FileName‘ with the name of the file you want to zip.
tar -a -c -f Compressed.zip FileName.FileExt
How to Zip Files Using Windows PowerShell
There are several viable ways to create zip files on Windows. One of these is through Windows PowerShell. However, the tar command doesn’t work in Windows PowerShell; we’ll use another command to get the work done.
Here’s how to zip files using Windows PowerShell:
- Open the Start Menu, type Windows PowerShell, and choose Run as administrator from the right pane.
-
In the console, type the following command and press Enter. Ensure to replace file destination and target location with the location of the file and the place where you want the file to be zipped, respectively. Also, replace file name with the name of the file you want to zip and destination name with the destination folder name.
Compress-Archive -LiteralPath 'file destination\file name' -DestinationPath 'target location\destination name'
If you want to zip multiple files, execute the following command. Replace file destination and file destination 1 with the location of the first and second files, respectively. And replace file name and file name 2 with the first and second file names.
Compress-Archive -LiteralPath 'file destination\file name', 'file destination 1\file name 2 -DestinationPath 'target location\destination name'
How to Unzip Files Using Command Prompt
There may be situations where you want to unzip files on your Windows computer. Fortunately, you can do that as well using Command Prompt. Here’s how:
- Launch Command Prompt with admin privileges.
- Use the cd command to head toward the zip file’s location.
-
Type the following command and press Enter. Replace ‘Name‘ with the name of the zip file.
tar -xf Name.zip
You’ve successfully unzipped the file.
How to Unzip Files Using Windows PowerShell
Windows PowerShell lets you quickly unzip files on your computer. Here’s how to do that:
- Open Windows PowerShell with admin rights.
-
Type the following command and press Enter. Make sure to replace <file destination> and <target location> with the location of the zip file and the place where you want the file to be unzipped, respectively.
Expand-Archive -LiteralPath <file destination> -DestinationPath <target location>
Save Up Space on Windows 11 by Zipping Your Files
As a Windows user, you will always come across situations where you want to zip or unzip files. However, if you don’t want to use a third-party tool, you can use Command Prompt and Windows PowerShell to quickly zip and unzip files on Windows using the above methods.
Meanwhile, you might be interested in learning a few important Command Prompt commands.
Обновлено:
Опубликовано:
Используемые термины: 7zip.
Приведенные ниже команды выполняются после перехода в каталог с установленным 7-Zip. Как правило:
cd «C:\Program Files\7-Zip»
В данной инструкции мы рассмотрим синтаксис команды 7z, а также приведем примеры ее использования.
Архивирование и разархивирование
Как распаковать
Как запаковать
Резервное копирование
Пример cmd-скрипта
Пример powershell-скрипта
Описание ключей и команд
Команды
Ключи
Примеры использования команд
Исключение файлов и папок
Архивирование базы 1С
Дополнительные материалы
Распаковать и заархивировать
Общий синтаксис:
7z <команда> <ключи> <пути к каталогам и файлам>
Синтаксис для распаковки:
7z <x или e> <архивный файл> -o»<путь, куда распаковываем>»
* ключ x распаковывает с сохранением каталожной структуры; e — все в одно место.
Пример:
7z x c:\temp\archive.7z -o»c:\temp\»
* в данном примере мы распакуем файл c:\temp\archive.7z в папку c:\temp
Архивация
Синтаксис для архивирования:
7z a <ключи> <архивный файл> <объект архивирования>
Например:
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-скрипта для резервного копирования:
@echo off
set source=»C:\Date»
set destination=»C:\Temp»
set passwd=»Password»
set dd=%DATE:~0,2%
set mm=%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 укажет работать в четыре потока. |
-m | Задает метод сжатия. Доступны варианты: — LZMA: базовый метод для сжатия 7z. Быстрое сжатие и декомпрессия. — LZMA2: метод по умолчанию для 7z. Поддерживает несколько процессорных потоков. — PPMd: метод PPMdH Дмитрия Шкарина с небольшими изменениями. Хорошо подходит для текстовых файлов. — BZip2: на основе алгоритма BWT. Также хорош для текстовых файлов. — Deflate: стандартный метод для форматов ZIP и GZip. Сжатие не очень хорошее, но высокая скорость работы. Поддерживает только 32 КБ словаря. — Deflate64: аналогичен Deflate, но с поддержкой 64 КБ словаря. |
Полный список ключей и команд можно получить командой 7z —help.
Примеры
Исключение файлов и папок
Отдельно стоит рассказать про возможность исключения. Есть два варианта ее применения.
Первый — создать список исключений в отдельном файле.
Пример команды 7z:
7z.exe a -tzip -ssw -mx9 -r0 -x@exclus.txt C:\Temp\backup.zip C:\Data
* где exclus.txt — файл с исключениями.
Пример файла с исключениями:
test
*.tmp
* в данном примере мы исключаем каталог с именем test и все файлы с расширением tmp.
Второй — указать исключение в команде.
7z.exe a -tzip -ssw -mx9 -r0 -xr!Шаблон* C:\Temp\backup.zip C:\Data
Резервирование баз 1С
Данные базы 1С находятся в файлах с расширением .1CD. Для их резервирования используем команду:
7z.exe a -tzip -mmt=2 -ssw -mx5 -r0 C:\Temp\backup.zip D:\Bases_1C\*.1CD
* в данном примере мы будем сжимать все файлы 1CD в архив C:\Temp\backup.zip.
Читайте также
Другая информация, близкая по теме:
1. Использование tar в Linux и FreeBSD для работы с архивами.
2. Резервное копирование MS SQL Server.
3. Пример скрипта для создания резервной копии файлового сервера.