Advertisement
anonit

Create a zip file using powershell

Apr 27th, 2015
599
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # Zip Backup
  2.  
  3. <#
  4. Creates a Zip file of a given folder in another location, with the date as the name.
  5.  
  6. Parameters:
  7. SourceLocation - Location of source files (no trailing slash required)
  8. DestinationLocation - Location of destination (folder - no trailing slash required)
  9. #>
  10.  
  11. $SourceLocation="\\server33\resources\forge"
  12. $DestinationLocation="e:\backup\forge"
  13.  
  14.  
  15. # Get date and time
  16. $TodaysDate=get-date -UFormat "%Y%m%d"
  17. $TodaysTime=get-date -UFormat "%H%M"
  18.  
  19.  
  20. # Set random directory to the users temp directory plus a random number
  21. $RandomDirectoryName=get-random
  22. $TemporaryLocation=$env:TEMP+"\"+$RandomDirectoryName
  23.  
  24. # Prepare the Destination file name and path
  25. $DestinationFile=$DestinationLocation+"\"+$TodaysDate+$TodaysTime+".zip"
  26.  
  27.  
  28. # if the temporary path already exists / exit with error
  29. if (!(Test-Path -path $TemporaryLocation))
  30. {
  31.     # Create the temporary location
  32.     new-item $TemporaryLocation -type directory
  33.    
  34.     # Copy the source to the destination
  35.     $CopyResults=copy-item $SourceLocation -destination $TemporaryLocation -recurse -passthru
  36.     if ($CopyResults)
  37.     {
  38.         # Compress the file
  39.         Add-Type -assembly System.IO.Compression.FileSystem
  40.         $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
  41.         [system.io.compression.zipfile]::CreateFromDirectory($TemporaryLocation,$DestinationFile,$CompressionLevel,$false)
  42.    
  43.         # Delete the temporary location
  44.         remove-item $TemporaryLocation -Force -recurse
  45.     }
  46.     else
  47.     {
  48.         # if the zip fails, produce error
  49.         write-host -BackgroundColor white -ForegroundColor red "Failed creating ZIP file"
  50.     }
  51. }
  52. else
  53. {
  54.     write-host -BackgroundColor white -ForegroundColor Red "Failed - temporary folder already exists.  Try again"
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement