Advertisement
Guest User

Untitled

a guest
Jul 13th, 2018
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ########################################################
  2. # Name: BackupScript.ps1                              
  3. # Creator: Michael Seidl aka Techguy                    
  4. # CreationDate: 21.01.2014                              
  5. # LastModified: 28.05.2018                              
  6. # Version: 1.3
  7. # Doc: http://www.techguy.at/tag/backupscript/
  8. # PSVersion tested: 3 and 4
  9. #
  10. # Description: Copies the Bakupdirs to the Destination
  11. # You can configure more than one Backupdirs, every Dir
  12. # wil be copied to the Destination. A Progress Bar
  13. # is showing the Status of copied MB to the total MB
  14. # Only Change Variables in Variables Section
  15. # Change LoggingLevel to 3 an get more output in Powershell Windows
  16. #
  17. #
  18. # Beschreibung: Kopiert die BackupDirs in den Destination
  19. # Ordner. Es können mehr als nur ein Ordner angegeben
  20. # werden. Der Prozess wid mit einem Statusbar angezeigt
  21. # diese zeigt die kopieren MB im Vergleich zu den gesamten
  22. # MB an.
  23. # Nur die Werte unter Variables ändern
  24. # Ändere den Logginglevel zu 3 und erhalte die gesamte Ausgabe im PS Fenster
  25. # Version 1.3 - NEW: Send Mail Function
  26. #               NEW: Backup Destination will be zipped
  27. #               NEW: Exclude Dir
  28. #               FIX: Logging Level
  29. #               FIX: Delete old Folder by CreationTime
  30. #
  31. # Version 1.2 - FIX: Delete last Backup dirs, changed to support older PS Version
  32. #               FIX: Fixed the Count in the Statusbar
  33. #               FIX: Fixed Location Count in Statusbar
  34. #
  35. # Version 1.1 - CHANGE: Enhanced the Logging to a Textfile and write output, copy Log file to Backupdir
  36. #             - FIX: Renamed some Variables an have done some cosmetic changes
  37. #             - CHANGE: Define the Log Name in Variables
  38. #
  39. # Version 1.0 - RTM
  40. ########################################################
  41. #
  42. # www.techguy.at                                        
  43. # www.facebook.com/TechguyAT                            
  44. # www.twitter.com/TechguyAT                            
  45. # michael@techguy.at
  46. ########################################################
  47.  
  48. #Variables, only Change here
  49. $Destination="C:\Temp" #Copy the Files to this Location
  50. $Versions="2" #How many of the last Backups you want to keep
  51. $BackupDirs="C:\Users\Micha\OneDrive", "C:\Program Files (x86)\OpenVPN" #What Folders you want to backup
  52. $ExcludeDirs="C:\Program Files (x86)\OpenVPN\bin", "C:\Program Files (x86)\OpenVPN\config" #This list of Directories will not be copied
  53. $LogName="Log.txt" #Log Name
  54. $LoggingLevel="3" #LoggingLevel only for Output in Powershell Window, 1=smart, 3=Heavy
  55. $Zip=$true #Zip the Backup Destination
  56. $RemoveBackupDestination=$false #Remove copied files after Zip, only if $Zip is true
  57.  
  58.  
  59. #Send Mail Settings
  60. $SendEmail = $false                    # = $true if you want to enable send report to e-mail (SMTP send)
  61. $EmailTo   = 'test@domain.com'              #user@domain.something (for multiple users use "User01 <user01@example.com>" ,"User02 <user02@example.com>" )
  62. $EmailFrom = 'from@domain.com'   #matthew@domain
  63. $EmailSMTP = 'smtp.domain.com' #smtp server adress, DNS hostname.
  64.  
  65.  
  66.  
  67. #STOP-no changes from here
  68. #STOP-no changes from here
  69. #Settings - do not change anything from here
  70. $Backupdir=$Destination +"\Backup-"+ (Get-Date -format yyyy-MM-dd)+"-"+(Get-Random -Maximum 100000)+"\"
  71. $Log=$Backupdir+$LogName
  72. $Items=0
  73. $Count=0
  74. $ErrorCount=0
  75. $StartDate=Get-Date #-format dd.MM.yyyy-HH:mm:ss
  76.  
  77. #FUNCTION
  78. #Logging
  79. Function Logging ($State, $Message) {
  80.     $Datum=Get-Date -format dd.MM.yyyy-HH:mm:ss
  81.  
  82.     if (!(Test-Path -Path $Log)) {
  83.         New-Item -Path $Log -ItemType File | Out-Null
  84.     }
  85.     $Text="$Datum - $State"+":"+" $Message"
  86.  
  87.     if ($LoggingLevel -eq "1" -and $Message -notmatch "was copied") {Write-Host $Text}
  88.     elseif ($LoggingLevel -eq "3") {Write-Host $Text}
  89.    
  90.     add-Content -Path $Log -Value $Text
  91.     sleep -Milliseconds 100
  92. }
  93.  
  94.  
  95. #Create Backupdir
  96. Function Create-Backupdir {
  97.     New-Item -Path $Backupdir -ItemType Directory | Out-Null
  98.     sleep -Seconds 3
  99.     Logging "INFO" "Create Backupdir $Backupdir"
  100. }
  101.  
  102. #Delete Backupdir
  103. Function Delete-Backupdir {
  104.     $Folder=Get-ChildItem $Destination | where {$_.Attributes -eq "Directory"} | Sort-Object -Property $_.CreationTime  -Descending:$true | Select-Object -First 1
  105.  
  106.     Logging "INFO" "Remove Dir: $Folder"
  107.    
  108.     $Folder.FullName | Remove-Item -Recurse -Force
  109. }
  110.  
  111.  
  112. #Delete Zip
  113. Function Delete-Zip {
  114.     $Zip=Get-ChildItem $Destination | where {$_.Attributes -eq "Archive" -and $_.Extension -eq ".zip"} | Sort-Object -Property $_.CreationTime  -Descending:$true | Select-Object -First 1
  115.  
  116.     Logging "INFO" "Remove Zip: $Zip"
  117.    
  118.     $Zip.FullName | Remove-Item -Recurse -Force
  119. }
  120.  
  121. #Check if Backupdirs and Destination is available
  122. function Check-Dir {
  123.     Logging "INFO" "Check if BackupDir and Destination exists"
  124.     if (!(Test-Path $BackupDirs)) {
  125.         return $false
  126.         Logging "Error" "$BackupDirs does not exist"
  127.     }
  128.     if (!(Test-Path $Destination)) {
  129.         return $false
  130.         Logging "Error" "$Destination does not exist"
  131.     }
  132. }
  133.  
  134. #Save all the Files
  135. Function Make-Backup {
  136.     Logging "INFO" "Started the Backup"
  137.     $Files=@()
  138.     $SumMB=0
  139.     $SumItems=0
  140.     $SumCount=0
  141.     $colItems=0
  142.     Logging "INFO" "Count all files and create the Top Level Directories"
  143.  
  144.     foreach ($Backup in $BackupDirs) {
  145.         $colItems = (Get-ChildItem $Backup -recurse | Where-Object {$_.mode -notmatch "h"} | Measure-Object -property length -sum)
  146.         $Items=0
  147.         $FilesCount += Get-ChildItem $Backup -Recurse | Where-Object {$_.mode -notmatch "h"}  
  148.         Copy-Item -Path $Backup -Destination $Backupdir -Force -ErrorAction SilentlyContinue
  149.         $SumMB+=$colItems.Sum.ToString()
  150.         $SumItems+=$colItems.Count
  151.     }
  152.  
  153.     $TotalMB="{0:N2}" -f ($SumMB / 1MB) + " MB of Files"
  154.     Logging "INFO" "There are $SumItems Files with  $TotalMB to copy"
  155.  
  156.     foreach ($Backup in $BackupDirs) {
  157.         $Index=$Backup.LastIndexOf("\")
  158.         $SplitBackup=$Backup.substring(0,$Index)
  159.         $Files = Get-ChildItem $Backup -Recurse | Where-Object {$_.mode -notmatch "h" -and $ExcludeDirs -notcontains $_.FullName}
  160.         foreach ($File in $Files) {
  161.             $restpath = $file.fullname.replace($SplitBackup,"")
  162.             try {
  163.                 Copy-Item  $file.fullname $($Backupdir+$restpath) -Force -ErrorAction SilentlyContinue |Out-Null
  164.                 Logging "INFO" "$file was copied"
  165.             }
  166.             catch {
  167.                 $ErrorCount++
  168.                 Logging "ERROR" "$file returned an error an was not copied"
  169.             }
  170.             $Items += (Get-item $file.fullname).Length
  171.             $status = "Copy file {0} of {1} and copied {3} MB of {4} MB: {2}" -f $count,$SumItems,$file.Name,("{0:N2}" -f ($Items / 1MB)).ToString(),("{0:N2}" -f ($SumMB / 1MB)).ToString()
  172.             $Index=[array]::IndexOf($BackupDirs,$Backup)+1
  173.             $Text="Copy data Location {0} of {1}" -f $Index ,$BackupDirs.Count
  174.             Write-Progress -Activity $Text $status -PercentComplete ($Items / $SumMB*100)  
  175.             if ($File.Attributes -ne "Directory") {$count++}
  176.         }
  177.     }
  178.     $SumCount+=$Count
  179.     $SumTotalMB="{0:N2}" -f ($Items / 1MB) + " MB of Files"
  180.     Logging "INFO" "----------------------"
  181.     Logging "INFO" "Copied $SumCount files with $SumTotalMB"
  182.     Logging "INFO" "$ErrorCount Files could not be copied"
  183.  
  184.  
  185.     # Send e-mail with reports as attachments
  186.     if ($SendEmail -eq $true) {
  187.         $EmailSubject = "Backup Email $(get-date -format MM.yyyy)"
  188.         $EmailBody = "Backup Script $(get-date -format MM.yyyy) (last Month).`nYours sincerely `Matthew - SYSTEM ADMINISTRATOR"
  189.         Logging "INFO" "Sending e-mail to $EmailTo from $EmailFrom (SMTPServer = $EmailSMTP) "
  190.         ### the attachment is $log
  191.         Send-MailMessage -To $EmailTo -From $EmailFrom -Subject $EmailSubject -Body $EmailBody -SmtpServer $EmailSMTP -attachment $Log
  192.     }
  193. }
  194.  
  195.  
  196. #Bcreate Backup Dir
  197. Create-Backupdir
  198. Logging "INFO" "----------------------"
  199. Logging "INFO" "Start the Script"
  200.  
  201. #Check if Backupdir needs to be cleaned and create Backupdir
  202. $Count=(Get-ChildItem $Destination | where {$_.Attributes -eq "Directory"}).count
  203. Logging "INFO" "Check if there are more than $Versions Directories in the Backupdir"
  204.  
  205. if ($count -gt $Versions) {
  206.  
  207.     Delete-Backupdir
  208.  
  209. }
  210.  
  211.  
  212. $CountZip=(Get-ChildItem $Destination | where {$_.Attributes -eq "Archive" -and $_.Extension -eq ".zip"}).count
  213. Logging "INFO" "Check if there are more than $Versions Zip in the Backupdir"
  214.  
  215. if ($CountZip -gt $Versions) {
  216.  
  217.     Delete-Zip
  218.  
  219. }
  220.  
  221. #Check if all Dir are existing and do the Backup
  222. $CheckDir=Check-Dir
  223.  
  224. if ($CheckDir -eq $false) {
  225.     Logging "ERROR" "One of the Directory are not available, Script has stopped"
  226. } else {
  227.     Make-Backup
  228.  
  229.     $Enddate=Get-Date #-format dd.MM.yyyy-HH:mm:ss
  230.     $span = $EndDate - $StartDate
  231.     $Minutes=$span.Minutes
  232.     $Seconds=$Span.Seconds
  233.  
  234.     Logging "INFO" "Backupduration $Minutes Minutes and $Seconds Seconds"
  235.     Logging "INFO" "----------------------"
  236.     Logging "INFO" "----------------------"
  237.  
  238.     if ($Zip)
  239.     {
  240.         Logging "INFO" "Compress thew Backup Destination"
  241.         Compress-Archive -Path $Backupdir -DestinationPath ($Destination+("\"+$Backupdir.Replace($Destination,'').Replace('\','')+".zip")) -CompressionLevel Optimal -Force
  242.  
  243.         If ($RemoveBackupDestination)
  244.         {
  245.             Logging "INFO" "Backupduration $Minutes Minutes and $Seconds Seconds"
  246.  
  247.             #Remove-Item -Path $BackupDir -Force -Recurse
  248.             get-childitem -Path $BackupDir -recurse -Force  | remove-item -Confirm:$false -Recurse
  249.             get-item -Path $BackupDir   | remove-item -Confirm:$false -Recurse
  250.         }
  251.     }
  252. }
  253.  
  254. Write-Host "Press any key to close ..."
  255.  
  256. $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement