I was having a frustrating time zipping files in a Powershell script, one that I had created based on those discussed in David Aiken’s blog post. The name of the zip files created were quite long and were being generated a 8.3 filename automatically whenever the CopyHere method was being called on the zip folder where the files were being added. It was certainly something related to this method, as the New-Zip function was creating the zip file with the desired name, but was renamed only after the CopyHere method was used.

Now I still haven’t found a solution to this problem so if anyone has any suggestions they are most welcome to post them. What I did do however was create a workaround which entails creating the zip file locally on the machine where the script is executing and then move this to the destination. It turns out this problem only happens when attempting to write to a network folder directly.

The following function had the issue with CopyHere

function Add-Zip
{
param([string]$zipfilename)

if(-not (test-path($zipfilename)))
{
set-content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
(dir $zipfilename).IsReadOnly = $false
}

# Return the application object
$shellApplication = new-object -com shell.application

# Returns a folder object for the specified folder
$zipPackage = $shellApplication.NameSpace($zipfilename)

# Returns file object for the zip file
$zip = Get-Item $zipfilename
$activity = 'Zipping file to ' + $zip.Name + ': '
foreach($file in $Input)
{
Write-Progress -activity $activity -status $file.Name
$zipPackage.CopyHere($file.FullName,256)
Start-sleep -milliseconds 500
}
}

So I simply created a temporary zip and then moved it

# For some reason the filename is getting trimmed when writing directly to the network, so
# we use a temporary folder here for storage before moving to the final destination
$filename = "$element-$(Get-Date -f dd-MMM-yy-HH-mm-ss)"
$zipPath = "$tempFolder\$filename.zip"

# Create a new zip file
New-Zip $zipPath
$path = $element.PSPath

# Add each item in this elements path to the zip file
Get-Item $element.PSPath | Add-Zip $zipPath

# Now move it to the final destination
Move-Item $zipPath $componentfolder