silverbackbg
silverbackbg

Reputation: 182

Zip multiple folders and files using powershell 2

I have the following structure of folders,subfolders and files inside each of them C:\Prod\FolderName1 C:\Prod\FolderName1XX C:\Prod\FolderName1YY C:\Prod\FolderName1ZZ

I would like to have all Foldername1 folders with their subfolders and files zipped into a single zip file.

The following works fine with powershell 5.0

$name = Read-Host 'enter the folder NAME'
$namexx = $name + 'xx'
$nameyy = $name + 'yy'
$namezz = $name + 'zz'

$fullpath = join-path -path 'C:\Prod\' -childpath $name
$fullpathxx = join-path -path 'C:\Prod\' -childpath $namexx
$fullpathyy = join-path -path 'C:\Prod\' -childpath $nameyy
$fullpathzz = join-path -path 'C:\Prod\' -childpath $namezz

Compress-Archive -LiteralPath $fullpath,$fullpathxx,$fullpathyy,$fullpathzz -CompressionLevel Optimal -DestinationPath "C:\Dev\$blue $(get-date -f yyyy-MM-dd).zip"

Unfortunately on the server where it has to happen the Powershell is version 2.0 and does not have the Compress-Archive cmdlet.

I tried

Add-Type -Assembly "System.IO.Compression.FileSystem" ;
[System.IO.Compression.ZipFile]::CreateFromDirectory("$fullpath", "c:\dev\$name.zip") ; 

but this approach creates multiple zip files for each of the folders. Thanks in advance.

Upvotes: 0

Views: 2207

Answers (1)

Christopher
Christopher

Reputation: 788

I was able to do this in 2.0 using the DotNetZip library.

You can find all the documentation/downloads you will need here: https://archive.codeplex.com/?p=dotnetzip

https://www.nuget.org/packages/DotNetZip/

https://github.com/haf/DotNetZip.Semverd

To implement it into a PS script, you'll want to do something like this:

[System.Reflection.Assembly]::LoadFrom("your \ path \ to \ the \ dll \ file") 

#To zip a file, do this: 
$zipObj = New-Object Ionic.Zip.Zipfile
$zipObj.AddFile($fileName, "file")
$zipObj.Save($saveFileName)
$zipObj.Dispose()

#To zip a directory, do this:
$zipObj = New-Object Ionic.Zip.Zipfile
$zipObj.AddDirectory($directoryName,"dir")
$zipObj.Save($saveDirectoryName)
$zipObj.Dispose()

Hope this helps! I know it's a pain having to depend on another tool - but this dll has really done wonders (and we continue to use it even though Powershell 4 is capable of zipping on it's own).

There is another good example here (with encryption): https://documentation.help/DotNetZip/Powershell.htm

EDIT: Codeplex is being taken down soon, and I hate when I click on a link that has been shutdown, so if anyone in the future is looking for this library, you can find it here:

https://www.nuget.org/packages/DotNetZip/

https://github.com/haf/DotNetZip.Semverd

Upvotes: 2

Related Questions