Controlled zip

Tags:
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