壓縮/解壓縮
指令 | 說明 |
---|
Compress-Archive | 壓縮 |
Expand-Archive | 解壓縮 |
2個指令的常用參數相似,見以下說明。
壓縮整個資料夾
1 2
| 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)
level | description |
---|
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
Code | Meaning |
---|
0 | No error |
1 | Warning (Non fatal error(s)). For example, one or more files were locked by some other application, so they were not compressed. |
2 | Fatal error |
7 | Command line error |
8 | Not enough memory for operation |
255 | User stopped the process |