Home/PowerShell/Use PowerShell to create compressed ZIP files

Use PowerShell to create compressed ZIP files

In many scenario we will have a requirement for handling to create zip archives or extract files from existing archives with programmatically .  From PowerShell 5.0, it has added two cmdlets for creating and extracting zip. The Compress-Archive cmdlet enables you to create new archives from folders or individual files and to add files to archives; Extract-Archive can be used to unzip files. Let we get in to this with very two simple example.

Example #1 : Create an Simple archive file

The below command will zip the Dotnethelpers_PowershellArticles folder and create an archive called PowershellArticles.zip in the Archives folder:

–Path : Parameter to specify the folder you want to compress
–DestinationPath : Parameter to specify the name of the archive you want to create.

Example: 2 : Create an archive file using -LiteralPath

The below command creates PowerShellMVCArticles.Zip file by compressing two folders that is Dotnethelpers_PowershellArticles and PowerShellMVCArticles.Zip specified by the LiteralPath parameter instead of -path cmdlet.

  • -LiteralPath: Instead of -Path cmdlet, it specify multiple paths, and include files in multiple locations in your output zipped file
  • -Update : If you not using the -update cmdlet for compressing the existing zip which having same name then we will get caught by the below error. In this scenario the we need to use  -Update cmdlet which will tells that please overwrite if file is already existing in the same destination location and update  compression with newer versions of existing files.
  • -CompressionLevel : Here i had mentioned the compression level as Optimal, this tells how much compression to apply when you are creating the archive file. If compression level parameter is not specified in our script the the command uses the default value as Optimal.

Fastest: This method available to decrease processing time; this can result in larger file sizes.
NoCompression: Do not compress the source files.
Optimal: Processing time is dependent on file size.

OUTPUT

Leave a Reply