Friday, January 13, 2012

7zip and PowerShell

 

Hi,

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 : http://www.7-zip.org/download.html

You can download the whole script from here : http://dl.dropbox.com/u/17858935/PowerShell_%26_7Zip.zip

-------------------------------------------------------------------------------------------------------------------------------------------------------------

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 = $file.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

1 

2 

3 

I hope it helps someone :)

Thanks

Aman Dhally

 

 

 

4 comments:

  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.

    like

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

    ReplyDelete
  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
    aman

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

    ReplyDelete
  4. Handy - thanks !

    ReplyDelete

Note: Only a member of this blog may post a comment.