johndoe
johndoe

Reputation: 35

How to zip all the files in a folder individually?

In powershell, how should I zip all the files in a folder individually ? For example, I have 10 files in a folder which means I want to have 10 zips.

Below is my code but it only zips one file.

Add-Type -Path "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.IO.Compression.FileSystem.dll"
function ZipFiles( $zipfilename, $sourcedir )
{
   Add-Type -Assembly System.IO.Compression.FileSystem
   $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
   [System.IO.Compression.ZipFile]::CreateFromDirectory($sourcedir,
        $zipfilename, $compressionLevel, $false)
}

ZipFiles "zippath" "sourcepath"

Upvotes: 2

Views: 11475

Answers (3)

Xinyo Chen
Xinyo Chen

Reputation: 36

use PowerShell go the the path that you would like to compress, do:

$folderlist = Get-ChildItem "."
foreach ($File in $folderlist) { Compress-Archive -path $File.Name -destinationPath "$($File.Name).zip"}

Upvotes: 2

TomTichy
TomTichy

Reputation: 597

Here is a one-liner that I just used that zips all files in the current directory using the filename and appending .zip extension

 Get-ChildItem "." | ForEach-Object { Compress-Archive -path $_.Name -destinationPath "$($_.Name).zip"}

Upvotes: 6

Nick
Nick

Reputation: 1863

  1. So we get a list of folders in a path (-Directory returns folders only)
  2. Then for each folder in the folderlist we pass it to the ZipFiles function
  3. Function call will look like: ZipFiles "C:\Logs.zip" "C:\Logs"

    $folderlist = Get-ChildItem -Path C:\ -Directory
    Foreach ($Folder in $folderlist)
    {ZipFiles "$($Folder.Fullname).zip" "$($Folder.Fullname)"}
    

Upvotes: 1

Related Questions