powershell

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"

Solution

    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)"}