Compress a Folder With a little bit of help from .NET Framework

Few weeks ago I needed to free some space form a disk on a Windows Server 20012 R2, so I wanted to compress a large number folders, each one of them contained few hundred MB of log files.  It required to preserve the folder name and deleting or moving the files or directory from that volume/partition was not an option.

It’s an easy task with PowerShell“, I thought, “I can re-use one of my functions or scripts“.

In fact, few months ago I’ve published an article on how to compress a folder, but to re-use that specific code on that environment I needed to install 7zip (which in this specific case I tried to avoid), because the cmd-let Compress-Archive was released with version 5 and the server is using PowerShell 4.  So I needed to revisit my script that wasn’t ready to go and solve my problem without a little tweak.

My solution was to point to directly to the ZipFile Class from the .NETFramework, using PowerShell.  As you can probably guess, the main advantage of using PowerShell is that can access directly .NET Framework if needed, PowerShell is built upon it. Just remember the difference with PowerShell 6 or later(or core) that are built upon .NET core. Then I’ve found another blog post of the scripting guys that were doing exactly the same, so I though that I was on the right track if their conclusions were the same.

So I’ve written a function tested for version of powershell / powershell core and os-independent.  A wrapper for the cmd-let Compress-Archive for version 5 and later (including powershell core) and leveraging the .NET Framework for older versions. In short, I try to my old scripts a backward compatibility feature, not just multi-platform.

Remember to import the function before call it, with the dot-sourcing method, and always read the docs:

If you don’t remember which powershell version is available on which OS… there is an interesting summary on 4sysops.com website that I recommend you to read.

I hope you find this article useful and if you have any question feel free to ask or contact me.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.