Controlled zip

Powershell v5 introduced the Compress- and Expand-Archive cmdlets which enabled you to manage compressed archives. I had a question about how you could control adding files to archives using a CSV file. This is how you do a controlled zip.

Start by creating a set of test data.

1..100 |
foreach {
   $file =  “File$psitem.txt”
   Get-Process | Out-File -FilePath $file

  $i = Get-Random -Minimum 1 -Maximum 4
   $zip = “Archive$”

  $props = @{
     FileName = $file
     Archive = $zip

  New-Object -TypeName PSObject -Property $props
} | Export-Csv -Path FilesToArchive.CSV –NoTypeInformation

I created a 100 files – name of the form FileN.txt and into each piped the output of Get-Process just so they weren’t empty.

I wanted 3 zip files – named

I used Get-Random to assign the zip file.

Create an object to with the file and archive and output to CSV

The CSV looks like this:

FileName    Archive    
——–    ——-    

To perform the zip

Import-Csv .\FilesToArchive.CSV |
foreach {
   Compress-Archive -Path $_.FileName -DestinationPath $_.Archive -Update

Read the CSV file and for each file add it to the appropriate archive. The –Update parameter on Compress-Archive is what allows you to add files to an existing archive.

This entry was posted in PowerShell v5. Bookmark the permalink.

Leave a Reply

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

You are commenting using your 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