(PowerShell)壓縮/解壓縮

壓縮/解壓縮

指令說明
Compress-Archive壓縮
Expand-Archive解壓縮

2個指令的常用參數相似,見以下說明。

壓縮整個資料夾

1
2
# 建立 Zip 壓縮檔
Compress-Archive -Path C:\Folder -DestinationPath C:\Archive.zip

壓縮多個檔案

1
2
# 壓縮多個檔案
Compress-Archive -Path C:\Folder\file.docx, C:\Folder\picture.png -DestinationPath C:\Archive.zip

更新壓縮檔(Update)/強制覆蓋(Force)

1
2
# 更新壓縮檔
Compress-Archive -Path C:\Folder\*.txt -Update -DestinationPath C:\Archive.zip
1
2
# 強制覆蓋
Compress-Archive -Path C:\Folder\*.txt -Force -DestinationPath C:\Archive.zip

指定壓縮層級(CompressionLevel)

leveldescription
Fastest最快速方式壓縮。(檔案較大)
NoCompression不壓縮
Optimal最佳化壓縮,此方式為預設值。(檔案較小)

若要減少壓縮時間,可以Fastest壓縮層級進行壓縮

1
Compress-Archive -Path C:\Folder -CompressionLevel Fastest -DestinationPath C:\Archive.zip

指名檔案名稱(LiteralPath)

大部分狀況下使用-Path可順利進行壓縮,若遇檔案名稱含有特殊字元或萬用字元等狀況,無法順利壓縮時,可改用-LiteralPath參數

1
Compress-Archive -LiteralPath D:\StrangeFileName.jpg -DestinationPath D:\MyArchive.zip

加密壓縮(7-Zip)

powershell內建的Compress-Archive指令並無加密功能,改用7-Zip可在壓縮時加上密碼。

1
2
3
4
5
6
7
8
9
10
11
12
13
$7zipPath = "$env:ProgramFiles\7-Zip\7z.exe"

if (-not (Test-Path -Path $7zipPath -PathType Leaf)) {
throw "7 zip file '$7zipPath' not found"
}

Set-Alias 7zip $7zipPath

$Source = "c:\BackupFrom\backMeUp.txt"
$Target = "c:\BackupFolder\backup.zip"
$pass = [System.Web.Security.Membership]::GeneratePassword(10,2)

7zip a -mx=9 $Target $Source -p$pass

Exit Codes from 7-Zip

CodeMeaning
0No error
1Warning (Non fatal error(s)). For example, one or more files were locked by some other application, so they were not compressed.
2Fatal error
7Command line error
8Not enough memory for operation
255User stopped the process