Have Write-Zip create file if it does not exist when using -Append

Topics: Developer Forum
Jun 17, 2011 at 2:09 AM


I'm trying to use Write-Zip to process a folder full of archived event log files, which creates multiple zip files - which may or may not already exist.

I first assumed that using the -Append parameter would automatically create the .zip file if it didn't already exist - turns out it doesn't. So as a result I have to do something like this:

$ArchiveFile = "C:\Archive.zip"
If (Test-Path $ArchiveFile) { 
  $Append = $True
} Else {
  $Append = $False
Write-Zip -Path *.txt -OutputPath $ArchiveFile -Append:$Append

Unless someone else can suggest a better way to do this? Unfortunately while this should work in theory I've found in practice it has problems. The archive file gets created ok the first time (with $Append = $False), but the second time the code is run (with $Append = $True) the files get added with the path information intact, resulting in duplicate files within the same archive :(.

For example, the file C:\temp\document.txt would exist within the archive as:

I tried getting around this using the -FlattenPaths parameter, but found this doesn't work either due to a known bug (http://pscx.codeplex.com/workitem/27848).

Developers - would it be possible to update the -Append parameter so that it automatically creates the archive if it doesn't exist? If you didn't want to change existing functionality, a new parameter could be added to specify the append behaviour, e.g. -CreateMissing.

I'm hoping if the Write-Zip command automatically created the archive, I wouldn't have the problem with duplicate files being added either...


Jun 17, 2011 at 2:47 AM

Just figured out a workaround to the issue I mentioned above with duplicate files being added to the archive. Instead of using a boolean to control the -Append switch, just create an empty .zip file first:

$ArchiveFile = "C:\Archive.zip"
If (!(Test-Path $ArchiveFile)) { Set-Content $ArchiveFile ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18)) }      
Write-Zip -Path *.txt -OutputPath $ArchiveFile -Append

This avoids the duplicate files by always using the -Append switch. The folder path info is still preserved, which I don't want - but I can live with that :).