介紹如何在 PowerShell 中使用 Compress-Archive 與 Expand-Archive 建立與解壓縮 Zip 檔案。
壓縮檔案或目錄
若要在 PowerShell 終將指定的檔案壓縮成 Zip 壓縮檔,可以使用 Compress-Archive 這一個 cmdlet,其基本用法如下:
# 將 Myfile1.txt, Myfile2.txt 檔案壓縮為 Archive.zip Compress-Archive -LiteralPath Myfile1.txt, Myfile2.txt -DestinationPath Archive.zip
其中 -LiteralPath 參數可以指定要壓縮的檔案,多個檔案路徑之間以逗號分隔,而 -DestinationPath 則是指定輸出的 Zip 壓縮檔路徑。
-LiteralPath 參數只能以固定檔名來指定檔案,若要使用萬用字元(*)來指定多個要進行壓縮的檔案,可以改用 -Path 參數:
# 將所有 myfile*.txt 壓縮為 Archive.zip Compress-Archive -Path Myfile*.txt -DestinationPath Archive.zip
壓縮目錄
若要壓縮指定的目錄,方法跟檔案相同:
# 將 Myfolder1, Myfolder2 目錄壓縮為 Archive.zip Compress-Archive -LiteralPath Myfolder1, Myfolder2 -DestinationPath Archive.zip
若要壓縮一個目錄之下的檔案或子目錄,常用的方式有以下幾種:
# 壓縮整個目錄(包含根目錄) Compress-Archive -Path C:\OfficeGuide -DestinationPath C:\Backup\Archive.zip # 壓縮目錄下所有檔案與子目錄(不包含根目錄) Compress-Archive -Path C:\OfficeGuide\* -DestinationPath C:\Backup\Archive.zip # 只壓縮目錄下的檔案(不包含根目錄與子目錄) Compress-Archive -Path C:\OfficeGuide\*.* -DestinationPath C:\Backup\Archive.zip
更新 Zip 壓縮檔
若要新的檔案更新至既有的 Zip 壓縮檔案中(例如更新備份檔),可以加上 -Update 參數:
# 更新壓縮檔內容 Compress-Archive -Path C:\OfficeGuide -Update -DestinationPath C:\Backup\Archive.zip
壓縮層級
使用 Compress-Archive 壓縮資料時可以使用 -CompressionLevel 參數指定壓縮層級,可用的選項有:
| 選項 | 說明 |
|---|---|
Fastest |
處理時間短,但檔案大小較大。 |
NoCompression |
完全不壓縮。 |
Optimal |
最佳壓縮(預設選項)。 |
若要加快壓縮處理速度,可以改用 Fastest 壓縮層級:
# 加快壓縮處理速度 Compress-Archive -Path Myfile*.txt -CompressionLevel Fastest -DestinationPath Archive.zip
解壓縮 Zip 壓縮檔
在 PowerShell 中若要解壓縮 Zip 壓縮檔,可以使用 Expand-Archive cmdlet:
# 解壓縮 Zip 壓縮檔 Expand-Archive -LiteralPath C:\Backup\Archive.zip -DestinationPath C:\OfficeGuide
參考資料:How-To Geek

