Friday, January 13, 2012

7zip and PowerShell



first of all “Happy New year” to all of you.

yesterday one of my colleague asked me to write to write a script which can zip .bak files but the zip files should be in same folder which original .bak exists.

Logic behind this is to compress .bak files {normally SQL backups} in there current folders so that they are easy to find.

after spending 2-3 hours i am successfully able to get this done.

First you can download and installs the 7zip from this link :

You can download the whole script from here :


if (-not (test-path "$env:ProgramFiles\7-Zip\7z.exe")) {throw "$env:ProgramFiles\7-Zip\7z.exe needed"}

set-alias sz "$env:ProgramFiles\7-Zip\7z.exe"

$filePath = "C:\Users\aman.dhally\Desktop\Desktop-2\ASD\Test-3"

$bak = Get-ChildItem -Recurse -Path $filePath | Where-Object { $_.Extension -eq ".bak" }

foreach ($file in $bak) {

                                  $name = $

                                  $directory = $file.DirectoryName

                                  $zipfile = $name.Replace(".bak",".7z")

                                  sz a -t7z "$directory\$zipfile" "$directory\$name"    



you need to change the $filePath with your path .

You can use the same script to compress any files

Output Screenshots




I hope it helps someone :)


Aman Dhally





  1. Hello

    This is a great script and helpfull.

    I wonder if it is possible that the user can decide to include a certain level of the file tree structure and zipp all the files also in the subfolders.


    level 1 = d:\logs #whithout subfolders
    level 2 d:\Logs\ # with subfolders

  2. Hi Jan
    Thanks for the nice comment. and i am glad that u like the script.

    I think its is possible but not sure how ;-) , will try to do it whenever i get time ..

    thanks again

  3. IS there any way that we can include some validation if file exists it should not be zipped.

  4. Handy - thanks !

  5. As for me, it will be useful for students to take a look here before writing essays. It will help you to get a title