I’m having a problem with using zip compression in a Powershell script. The code snippet in question is:
$zipfile = $targetFile
$file = 'Script.ps1'
$stream = New-Object IO.FileStream($zipfile, [IO.FileMode]::Open)
$mode = [System.IO.Compression.ZipArchiveMode]::Update
$zip = New-Object IO.Compression.ZipArchive($stream, $mode)
($zip.Entries | ? { $file -contains $_.Name }) | % { $_.Delete() }
# Add a newer Script.ps1 file with the new Comment Based Help template.
$newFile = "$PSScriptRoot\$file"
[System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,$newFile,"Script.ps1","optimal")
# Clean up.
$zip.Dispose()
$stream.Close()
$stream.Dispose()
The code attempts to delete a file from the archive and then add a newer version of the same file. When I run the script, I receive the following:
[ERROR] Unable to find type [System.IO.Compression.ZipArchiveMode]. Make sure that the [ERROR] assembly that contains this type is loaded. [ERROR] At C:\xxxxx\xxxxx\xxxxx\PowerShellIDEInstallers\PowerShel [ERROR] lIDEInstallers\VSInstallCBH.ps1:141 char:2 [ERROR] + $mode = [System.IO.Compression.ZipArchiveMode]::Update [ERROR] +
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [ERROR] + CategoryInfo : InvalidOperation: (System.IO.Compression.ZipArch [ERROR] iveMode:TypeName) [], RuntimeException [ERROR] + FullyQualifiedErrorId : TypeNotFound [ERROR]
However, if I run it again, it will work correctly. I found a few posts (this and this) that spoke of similar problems. I’m currently using:
Add-Type -AssemblyName System.IO.Compression.FileSystem
At the top of the script. I also found this post which looked promising, but, did not work. I should also add that the problem occurs in the ISE, Visual Studio, and the command prompt. The code will work if I run it a second time in any of the environments.
I’m baffled and at a loss. Can anyone tell me why this is happening?