

野外求生系列 - PowerShell 壓縮 ZIP 檔
source link: https://blog.darkthread.net/blog/zip-with-ps/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

同事在 Windows 10 高高興興寫了壓縮檔案的 PowerShell 小工具,丟上伺服器執行時踢到鐵板。
PowerShell 有個 Compress-Archive Cmdlet 可壓縮 ZIP 檔,甚至能串接 PowerShell 輸出管線,例如:Get-ChildItem -Path C:\Reference\Afile.txt, C:\Reference\Images\Bfile.txt | Compress-Archive -DestinationPath C:\Archives\PipelineFiles.zip
,寫起來道地又方便。但有個問題 - Compress-Archive 要 PowerShell 5.0+ 才能用,Windows Server 2012R2 內建的 PowerShell 版本還是 4.0,登楞!
這次遇到的狀況也偏野外求生,希望做到不安裝或升級軟體、不部署工具程式,就地取材靠 Notepad 就完成任務。
PowerShell 寫了一陣子,現在的我已能淡定面對這類狀況,舉凡 PowerShell 做不到的事,交給 .NET 就對了。C# 既出,誰與爭鋒?
.NET 4.5 起加入 System.IO.Compression 命名空間工具組,其中 ZipFile.CreateFromDirectory() 能直接將整個資料夾壓成 ZIP,最接近我們的需求。所以,原本的 Compress-Archive 指令:
Compress-Archive -Path .\source\*.* -DestinationPath .\src-cmdlet.zip -CompressionLevel Optimal
可簡單改寫成:
Add-Type -AssemblyName System.IO.Compression
[System.IO.Compression.ZipFile]::CreateFromDirectory(".\source", ".\src-dotnet.zip", [System.IO.Compression.CompressionLevel]::Optimal, $true)
沒流什麼汗就解決囉。
不過,測試過程發現 Compress-Archive 有個缺點,CreateFromDirectory() 有個 bool includeBaseDirectory 參數能決定 ZIP 中的檔案要不要包含基底目錄(本例為 source,可參考下圖的差異),但 Compress-Archive 沒得選擇,source 底下的清單直接出現在 ZIP 根目錄:
查了一下,這是已知問題,大家常用的解法是先建個暫存目錄把 source 放進去,改壓縮暫存目錄以模擬 source 層,之後再清掉暫存目錄,說來挺鳥的,但也是種解法啦。如果是我,會選擇改用 .NET ZipFile.CreateFromDirectory() 較省事。
- Posted in
- PowerShell
Comments
Be the first to post a comment
Post a comment
CommentRecommend
-
48
8月12日夜,从杭州东开往北京南的G40次高铁,在运行中受大风刮起的彩钢板撞击,发生设备故障。13日4时许,北京铁路局官微发布最新进展:8月13日3时59分,受大风刮起彩钢板撞击造成的京沪高铁廊坊至北京南间设备故障已排除,列车恢复运行。
-
32
文档信息 编号 QiAnXinTI-SV-2019-0006 关键字 RDP CVE-2019-0708 发布日期 2019年05月15日 更新日期 2019年11月02日 TLP WHITE 分析团队 奇安信病毒响应中心 通告...
-
15
-
17
磐创AI分享 作者 | Aishwarya Srinivasan 编译 | VK 来源 | Towards Data Science
-
6
北京高校户外联盟的一日野外活动等级划分 作者: 张志强 ...
-
8
古代开在荒郊野外的驿站是什么来头?不会很危险吗?本文来自微信公众号:国家人文历史(ID:gjrwls),作者:番茄汁,编辑:詹茜卉,校对:李栋,题图来自:《龙门飞甲》徐克...
-
19
我們最近幾年幾乎所有案子都導入 CI/CD,把所有能自動化的工作全部都指令化,所以只要公司需要開發時期用的測試機,或是客戶需要安裝主機,通常都可以在 10 分鐘內搞定所有環境與設定。今天這篇文章我要來分享幾個常用的 7-Zi...
-
21
用在 IoT 裝置上的壓縮演算法 Heatshrink 在「Heatshrink – An ultra-lightweight compression library for em...
-
18
PostgreSQL 14 支援的 LZ4 壓縮 在 Hacker News 上看到 PostgreSQL 14 新支援的
-
10
內嵌 .js GZIP 壓縮檔-黑暗執行緒 繼續我的 HTML 文件檔計劃。封裝文件檔的另一項重點是把所有內容打包成單一 .html 檔 (高年級同學可能還記得 I...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK