The following example is retraceable on the internet and on this website as a sollution to compress files using the .NET Framework 4.5 It works, but when the archive already exists it will give an error, as it only seems to be able to zip a folder and create a new zip file:
[Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" )
$src_folder = "D:\stuff"
$destfile = "D:\stuff.zip"
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
$includebasedir = $false
[System.IO.Compression.ZipFile]::CreateFromDirectory($src_folder,$destfile,$compressionLevel, $includebasedir )
I already tried [System.IO.Compression.ZipFileExtensions], but then you can add files to an existing archive, but only by adding them separately, no folders or wildcards are allowed:
[Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" )
$src_folder = "D:\stuff" #also tried D:\stuff\ or D:stuff\*
$destfile = "D:\stuff.zip"
$destfile2=[System.IO.Compression.ZipFile]::Open($destfile, "Update")
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
[System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($destfile2,$src_folder,"\",$compressionlevel)
$archiver.Dispose()
I've created the script to proces files separately, but it takes a long time to process with more then a couple of thousand files in the same archive, so my question: Is there a way to add a complete folder to an existing zip archive at once?
BTW, I'm surprised how fast the System.IO.Compression.ZipFile is, excellent.
After looking at Noam's answer I realised how easy it is, I resolved my issue like this:
[Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" )
$src_folder = "D:\stuff\"
$destfile = "D:\stuff.zip"
$destfile2=[System.IO.Compression.ZipFile]::Open($destfile, "Update")
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
$in = Get-ChildItem $src_folder -Recurse | where {!$_.PsisContainer}| select -expand fullName
[array]$files = $in
ForEach ($file In $files)
{
$file2 = $file #whatever you want to call it in the zip
$null = [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($destfile2,$file,$file2,$compressionlevel)
}
$archiver.Dispose()