Sunday 24 February 2013

New-ZipFromDirectory.ps1


  1. <# 
  2. .SYNOPSIS 
  3.     Creates a new zip file from an existing folder 
  4. .DESCRIPTION 
  5.     This script uses the .NET 4.5 zipfile class  
  6.     to create a zip file, getting contents from  
  7.     a folder. 
  8. .NOTES 
  9.     File Name  : New-ZipfromDirectory 
  10.     Author     : Thomas Lee - tfl@psp.co.uk 
  11.     Requires   : PowerShell Version 3.0 and .NET 4.5 
  12. .LINK 
  13.     This script posted to: 
  14.         http://www.pshscripts.blogspot.com 
  15. .EXAMPLE 
  16.     Psh> C:\foo\new-zip.ps1 
  17.     Zip file created: 
  18.      
  19.     Directory: C:\foo 
  20.          
  21.     Mode                LastWriteTime     Length Name 
  22.     ----                -------------     ------ ---- 
  23.     -a---         2/24/2013   3:00 PM     291182 ScriptLib.ZIP 
  24.  
  25. #> 
  26.  
  27. # Load the compression namespace 
  28. # and yes, I know this usage is obsolete - but it works. 
  29. # Ignore the output 
  30. [System.Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem') | Out-Null  
  31.  
  32. # Create a type accellerator for the zipfile class 
  33. [System.Type] $TypeAcceleratorsType=[System.Management.Automation.PSObject].Assembly.GetType('System.Management.Automation.TypeAccelerators',$True,$True) 
  34. $TypeAcceleratorsType::Add('Zipfile','System.IO.Compression.Zipfile'
  35.  
  36. # Now create a zip file 
  37. # Set target zip flie and source folder 
  38. $Folder  = 'E:\PowerShellScriptLib' 
  39. $Zipfile = 'C:\foo\ScriptLib.ZIP' 
  40.  
  41. # Ensure file does NOT exist and fodler DOES exist 
  42. If (Test-Path $zipfile -EA -0) { 
  43.    Throw "$Zipfile exists - not safe to continue"
  44. If (!(Test-Path $folder)) { 
  45.    Throw "$Folder does not seem to exist"
  46.     
  47. # Now create the Zip file 
  48. Try { 
  49.   [Zipfile]::CreateFromDirectory( $folder, $zipfile) 
  50.   "Zip file created:";ls $zipfile} 
  51. Catch { 
  52.   "Zip File NOT created" 
  53.   $Error[0]} 

3 comments:

Mombo said...

Error on line 45. Your Throw call is inside the message string quotes

Mombo said...

Error on line 45. Your Throw call is inside the message string quotes.

Thomas Lee said...

Thanks - I have corrected this error. Good catch