PowerShell for Windows Admins

Feb 23 2018   2:30PM GMT

Controlled zip

Richard Siddaway Richard Siddaway Profile: Richard Siddaway


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$i.zip”

$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 ArchiveN.zip

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
——– ——-
File1.txt Archive1.zip
File2.txt Archive3.zip
File3.txt Archive1.zip
File4.txt Archive2.zip
File5.txt Archive1.zip
File6.txt Archive3.zip

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.

 Comment on this Post

There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: