Rajiv Ahmed
Rajiv Ahmed

Reputation: 3

Zip Multiple Folders Individually - Folder Structure

I've made the following code to zip up multiple folders in a directory into their own individual zip files.

#Current path to directory
$fileLocation = read-host "Type/Paste location"
$zipFilesPath = cd "$fileLocation"
$currentDirectory = pwd

$source = Get-ChildItem -Path $currentDirectory -Directory
gci | Where-Object{($_.PSIsContainer)} | foreach-object{$_.Name}

Add-Type -assembly "system.io.compression.filesystem"

Foreach ($s in $source) {
    $zipDestination = Join-path -path $currentDirectory -ChildPath "$($s.name).zip"

    If(Test-path $zipDestination){
        Remove-item $zipDestination
    }
    [io.compression.zipfile]::CreateFromDirectory($s.fullname, $zipDestination)
}

#Clear Console
clear
#Read-Host -Prompt “Press Enter to exit”
start .\

The individual zipping part works - took me a while but I managed to get it done.

E.g. zipfolder1

zipfolder2

zipfolder3

zipfolder1.zip

zipfolder2.zip

zipfolder3.zip

My problem is that when I zip, I don't simply want it to loop through the folders and zip the contents in the folders but instead zip the folder as is.

What the script currently outputs:

zipfolder1.zip > [files in zip taken from zipfolder1 folder]

What I want it to output:

zipfolder.zip > zipfolder1 > [files in zip taken from zipfolder1 folder]

Would this be possible to do? Basically I want to keep the folder itself in the zip - not just the contents

Upvotes: 0

Views: 3286

Answers (1)

Adam
Adam

Reputation: 4178

I'd just use the Compress-Archive commandlet:

$fileLocation = read-host "Type/Paste location"
$directories = Get-ChildItem -Path $fileLocation -Directory

foreach ($directory in $directories) {
    Compress-Archive -Path $directory.FullName -DestinationPath "$($directory.FullName).zip" -Force
}

Note, this will only compress a directory if there is something in it to compress.

Upvotes: 1

Related Questions