PowerShell Script to Compress Files Quickly
Compress-Archive -Path 'files' -DestinationPath 'archive.zip' in PowerShell to compress files into a ZIP archive quickly.Examples
How to Think About It
Compress-Archive cmdlet specifying the source and the destination ZIP file. This cmdlet handles creating the ZIP file and adding the files automatically.Algorithm
Code
Compress-Archive -Path 'C:\Example\*' -DestinationPath 'C:\Example\archive.zip' Write-Output "Files compressed to archive.zip"
Dry Run
Let's trace compressing all files in C:\Example to archive.zip
Identify files
Files in C:\Example: file1.txt, file2.txt
Run Compress-Archive
Compress-Archive -Path 'C:\Example\*' -DestinationPath 'C:\Example\archive.zip'
Output confirmation
Write-Output "Files compressed to archive.zip"
| Step | Action | Value |
|---|---|---|
| 1 | Files found | file1.txt, file2.txt |
| 2 | ZIP created | archive.zip with file1.txt, file2.txt |
| 3 | Output | Files compressed to archive.zip |
Why This Works
Step 1: Using Compress-Archive
The Compress-Archive cmdlet is built into PowerShell and compresses files or folders into a ZIP file.
Step 2: Specifying paths
You provide the source files with -Path and the ZIP file location with -DestinationPath.
Step 3: Output confirmation
Using Write-Output prints a message confirming the compression completed.
Alternative Approaches
[System.IO.Compression.ZipFile]::CreateFromDirectory('C:\Example', 'C:\Example\archive.zip') Write-Output "Compressed using .NET method"
Start-Process -FilePath '7z.exe' -ArgumentList 'a', 'C:\Example\archive.zip', 'C:\Example\*' -Wait Write-Output "Compressed using 7-Zip"
Complexity: O(n) time, O(n) space
Time Complexity
The time depends on the number of files n being compressed because each file is read and added to the archive.
Space Complexity
The space needed is proportional to the total size of files compressed, as the ZIP archive stores all data.
Which Approach is Fastest?
Using Compress-Archive is fast and simple for most cases; .NET methods may be slightly faster for large folders, while 7-Zip offers better compression but requires extra setup.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Compress-Archive cmdlet | O(n) | O(n) | Simple built-in compression |
| .NET ZipFile method | O(n) | O(n) | Compressing entire folders programmatically |
| 7-Zip command line | O(n) | O(n) | Advanced compression with external tool |
* in -Path to compress multiple files easily.* when specifying a folder path causes no files to be compressed.