Zipping Files in PowerShell

This sample defines a PowerShell function that zips all files in a directory:

                                        
  Function Zip-FilesInDirectory([string]$path,[string]$zipFileName) {

   # Load the assembly to use for Zipping files
   [Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem")
   
   # Get the Optimal CompressionLevel enum
   $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal

   # Perform the Zip operation
   [System.IO.Compression.ZipFile]::CreateFromDirectory($path,
        $zipFileName, $compressionLevel, $false)
  }

                                        

This function is useful if you want to automate the zipping of files in a directory. This function could be used with another script to zip a collection of files and then deliver them to network location.

Examples of using this sample:

                                        
  C:\Windows\system32> Zip-FilesInDirectory "C:\Files\" "C:\Files\MyZippedFiles.zip"

                                        

Bonus Tip:

This function requires at least PowerShell V3 and .NET 4.5 to be installed. If you only specify a name for the $zipFileName parameter the zip file will be placed in your current working directory.

                                        


© 2019 Embrs.net