3

I would to have PowerShell zip the contents of a bunch of folders and get an individual ZIP file for each folder. Recently, I asked how to do this with a .bat file and an answer was provided.

for /D %%d in (*.*) do "C:\Program Files\7-Zip\7z\7za.exe" a -tzip %%d.zip %%d

However, this proved useful only for folders that have no spaces in their name. The reason being that batch will do the following: if the folder name is "Jeff's vacation pictures", the variables will be:

%%d = Jeff's<br>
%%e = vacation<br>
%%f = pictures<br>

And then it tries to pass only %%d to the 7-Zip program, which will not find such a folder and therefore will not create a ZIP file.

I've tried looking up some tutorials, documentation sites and such, but I haven't been able to come up with an answer. There may be an answer, but I want to take this opportunity to try my hand at PowerShell.

I was thinking that a function with one argument, that being the parent-folder of the sub-folders that need to be zipped, would be the best approach.

So here's what I have, which doesn't work, probably due to my general inexperience with PowerShell:

function zipFolders($parent) {
    $zip = "C:\Program Files\7-Zip\7z\7za.exe";
    $parents | ForEach-Object $zip a -tzip
}
2
  • I don't now about powershell, but for the batch file try rapping the use of %%d in quotes ("%%d", "%%d.zip"). Good luck with Powershell, I need to learn it too. Jan 30, 2010 at 18:37
  • Yeah, the person who wrote it updated the old answer with that.
    – KdgDev
    Jan 31, 2010 at 0:50

1 Answer 1

4

You need to give 7-Zip an output file name and the name of the input directory for it to work. You also want to call Get-ChildItem (dir) on your parent path to get its subpaths.

The following snippet should put each subfolder of $rootFolder into a max compression ZIP file named after the subfolder in the current path.

dir $rootFolder | Where-Object { $_.PSIsContainer } | ForEach-Object { C:\"Program Files"\7-zip\7z.exe a -mx9 "$_.zip" $_.FullName }
3
  • Is this code correct? There is no feedback as to the value of this answer.
    – Russell
    Nov 4, 2010 at 2:36
  • @Russell: The PowerShell code itself looks right to me. However, I don't know the command line arguments to 7Zip, so you might have to tweak the part between the curly braces for your particular case. Dec 7, 2010 at 19:31
  • Tried this script while trying to write a PS script to run git pull in a set of folders. The recursion works but the 7z command does not (Error:incorrect command line), at least not in the version I have (PowerShell 2, 7z version 7).
    – calenti
    Jun 8, 2012 at 8:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .