PowerShell zip file

PowerShell zip fileIn the previous post I have  illustrated how to use PowerShell to remove old log files or directory from a given path, in this post I will illustrate how to use PowerShell to zip files or directories.

PowerShell zip file – The native way

In the post I will not describe the process of using third-party tools, like 7zip, to compress a folder or file as you can find plenty of examples and scripts to do so, what I am going to show it how to use PowerShell zip file native tools.

While PowerShell support to zip files has been, and continues to be, pretty weak if you’re running PowerShell 3 and .Net Framework 4.5 you can use native libraries and method to zip files and directories the following:

# Load necessary .Net libraries 
[Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" )

# Define the folder to be zipped 
$srcFolder = "D:MyLogs"

# Define destination zip file
$dstZip= "D:BackupLogs.zip"

# Use best compression level 
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal

# Change to $true if you want to include the base directory, defaults to $false
$includebasedir = $false

# Finally invoke the method to create the zip file
[System.IO.Compression.ZipFile]::CreateFromDirectory($srcfolder,$dstZip,$compressionLevel, $includebasedir)

As you can see using native .Net libraries is really easy to use PowerShell zip a file or folder and the above code can be easily adjusted and integrated into scripts so to automatically compress old files before they are rotated/deleted.

Full documentation for the CompressionLevel library can be found here http://goo.gl/HUilSf


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s