Advertisement
DistNZ

Beta_backupscript

Apr 17th, 2025
247
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # PowerShell Backup Script with Progress Indicator, Email Notifications, and Logging
  2.  
  3. # Load Config from JSON file
  4. $configFile = ".\config.json"
  5. $config = Get-Content $configFile | ConvertFrom-Json
  6.  
  7. # General Settings
  8. $PlexServerName = $config.General.PlexServerName
  9. $backupDestination = $config.General.BackupDestination
  10. $tempBackupDir = $config.General.TempBackupDir
  11. $logDir = $config.General.LogDir
  12. $sevenZipPath = $config.General.SevenZipPath
  13. $logRetentionDays = [int]$config.General.LogRetentionDays
  14. $backupRetentionCount = [int]$config.General.BackupRetentionCount
  15.  
  16. # Email Settings
  17. $emailTo = $config.Email.To
  18. $emailFrom = $config.Email.From
  19. $emailUsername = $config.Email.Username
  20. $emailPassword = $config.Email.Password
  21. $smtpServer = $config.Email.SmtpServer
  22. $smtpPort = $config.Email.SmtpPort
  23. $useSsl = $config.Email.UseSsl
  24.  
  25. # Source Directories
  26. $sources = $config.Sources
  27.  
  28. # Log File and Directory Setup
  29. $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
  30. $logFileDir = $logDir
  31. $logFile = Join-Path $logFileDir "PlexServerBackup_$timestamp.log"
  32.  
  33. # Start logging
  34. Start-Transcript -Path $logFile
  35.  
  36. # Create log directory if it doesn't exist
  37. if (-not (Test-Path $logFileDir)) {
  38.     New-Item -ItemType Directory -Force -Path $logFileDir
  39. }
  40.  
  41. # Helper function to send emails
  42. function Send-Email {
  43.     param(
  44.         [string]$subject,
  45.         [string]$body
  46.     )
  47.  
  48.     $mailMessage = New-Object system.net.mail.mailmessage
  49.     $mailMessage.From = ($emailFrom)
  50.     $mailMessage.To.Add($emailTo)
  51.     $mailMessage.Subject = $subject
  52.     $mailMessage.Body = $body
  53.     $mailMessage.IsBodyHtml = $true
  54.  
  55.     $smtp = New-Object Net.Mail.SmtpClient($smtpServer, $smtpPort)
  56.     $smtp.Credentials = New-Object System.Net.NetworkCredential($emailUsername, $emailPassword)
  57.     $smtp.EnableSsl = $useSsl
  58.     $smtp.Send($mailMessage)
  59. }
  60.  
  61. # Backup Process with Progress Bar
  62. $totalSources = $sources.PSObject.Properties.Count
  63. $counter = 0
  64. $backupSuccess = $true
  65.  
  66. foreach ($name in $sources.PSObject.Properties.Name) {
  67.     $counter++
  68.     $sourcePath = $sources.$name
  69.  
  70.     # Display Progress
  71.     $percentageComplete = ($counter / $totalSources) * 100
  72.     $progressBar = "[" + ("#" * [math]::Round($percentageComplete / 5)) + (" " * (20 - [math]::Round($percentageComplete / 5))) + "]"
  73.     Write-Host "`rProgress: $progressBar $($percentageComplete.ToString("F2"))% - Backing up $name..." -NoNewline
  74.  
  75.     if (Test-Path $sourcePath) {
  76.         # Backup using robocopy
  77.         $robocopyLog = Join-Path $tempBackupDir "$name-robocopy.log"
  78.         robocopy $sourcePath $tempBackupDir /E /Z /COPYALL /R:3 /W:5 | Out-File -Append -FilePath $robocopyLog
  79.         Add-Content -Path $logFile -Value "Robocopy log for $name: $robocopyLog"
  80.     } else {
  81.         Write-Host "`rProgress: $progressBar $($percentageComplete.ToString("F2"))% - Skipping $name: Source not found" -NoNewline
  82.         Add-Content -Path $logFile -Value "[$(Get-Date)] Skipping $name: Source not found"
  83.         $backupSuccess = $false
  84.     }
  85. }
  86.  
  87. Write-Host "`rProgress: [####################] 100% - Backup complete!"
  88.  
  89. # Compress the backup into a single ZIP file
  90. $zipFile = Join-Path $tempBackupDir "$PlexServerName_Backup_$timestamp.zip"
  91. & $sevenZipPath a -tzip $zipFile $tempBackupDir\* -r
  92.  
  93. # Move ZIP file to the destination
  94. if (Test-Path $zipFile) {
  95.     Move-Item -Path $zipFile -Destination $backupDestination
  96.     Add-Content -Path $logFile -Value "[$(Get-Date)] Backup moved to $backupDestination"
  97. } else {
  98.     $backupSuccess = $false
  99.     Add-Content -Path $logFile -Value "[$(Get-Date)] Backup failed: ZIP file not created"
  100. }
  101.  
  102. # Delete temp backup files after moving the ZIP
  103. Remove-Item -Path $tempBackupDir\* -Recurse
  104.  
  105. # Send success or failure email
  106. if ($backupSuccess) {
  107.     $emailSubject = "[$PlexServerName] Backup Success"
  108.     $emailBody = "<html><body><h1 style='color:green;'>Backup completed successfully!</h1><p>The backup process for Plex Server was completed successfully. The backup has been moved to the backup destination.</p></body></html>"
  109. } else {
  110.     $emailSubject = "[$PlexServerName] Backup Failed"
  111.     $emailBody = "<html><body><h1 style='color:red;'>Backup failed!</h1><p>The backup process for Plex Server encountered issues. Please review the logs for more details.</p></body></html>"
  112. }
  113.  
  114. # Send email
  115. Send-Email -subject $emailSubject -body $emailBody
  116.  
  117. # Retain log files based on retention policy
  118. $logFiles = Get-ChildItem -Path $logFileDir -Filter "PlexServerBackup_*.log" | Sort-Object LastWriteTime
  119. if ($logFiles.Count -gt $backupRetentionCount) {
  120.     $logsToDelete = $logFiles | Select-Object -Skip $backupRetentionCount
  121.     $logsToDelete | ForEach-Object { Remove-Item $_.FullName }
  122. }
  123.  
  124. # Delete logs older than the retention period
  125. $oldLogs = Get-ChildItem -Path $logFileDir -Filter "PlexServerBackup_*.log" | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$logRetentionDays) }
  126. $oldLogs | ForEach-Object { Remove-Item $_.FullName }
  127.  
  128. Stop-Transcript
  129.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement