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