Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # PowerShell Backup Script with Progress Indicator, Email Notifications, and Logging
- # Load Config from JSON file
- $configFile = ".\config.json"
- $config = Get-Content $configFile | ConvertFrom-Json
- # General Settings
- $PlexServerName = $config.General.PlexServerName
- $backupDestination = $config.General.BackupDestination
- $tempBackupDir = $config.General.TempBackupDir
- $logDir = $config.General.LogDir
- $sevenZipPath = $config.General.SevenZipPath
- $logRetentionDays = [int]$config.General.LogRetentionDays
- $backupRetentionCount = [int]$config.General.BackupRetentionCount
- # Email Settings
- $emailTo = $config.Email.To
- $emailFrom = $config.Email.From
- $emailUsername = $config.Email.Username
- $emailPassword = $config.Email.Password
- $smtpServer = $config.Email.SmtpServer
- $smtpPort = $config.Email.SmtpPort
- $useSsl = $config.Email.UseSsl
- # Source Directories
- $sources = $config.Sources
- # Log File and Directory Setup
- $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
- $logFileDir = $logDir
- $logFile = Join-Path $logFileDir "PlexServerBackup_$timestamp.log"
- # Start logging
- Start-Transcript -Path $logFile
- # Create log directory if it doesn't exist
- if (-not (Test-Path $logFileDir)) {
- New-Item -ItemType Directory -Force -Path $logFileDir
- }
- # Helper function to send emails
- function Send-Email {
- param(
- [string]$subject,
- [string]$body
- )
- $mailMessage = New-Object system.net.mail.mailmessage
- $mailMessage.From = ($emailFrom)
- $mailMessage.To.Add($emailTo)
- $mailMessage.Subject = $subject
- $mailMessage.Body = $body
- $mailMessage.IsBodyHtml = $true
- $smtp = New-Object Net.Mail.SmtpClient($smtpServer, $smtpPort)
- $smtp.Credentials = New-Object System.Net.NetworkCredential($emailUsername, $emailPassword)
- $smtp.EnableSsl = $useSsl
- $smtp.Send($mailMessage)
- }
- # Backup Process with Progress Bar
- $totalSources = $sources.PSObject.Properties.Count
- $counter = 0
- $backupSuccess = $true
- foreach ($name in $sources.PSObject.Properties.Name) {
- $counter++
- $sourcePath = $sources.$name
- # Display Progress
- $percentageComplete = ($counter / $totalSources) * 100
- $progressBar = "[" + ("#" * [math]::Round($percentageComplete / 5)) + (" " * (20 - [math]::Round($percentageComplete / 5))) + "]"
- Write-Host "`rProgress: $progressBar $($percentageComplete.ToString("F2"))% - Backing up $name..." -NoNewline
- if (Test-Path $sourcePath) {
- # Backup using robocopy
- $robocopyLog = Join-Path $tempBackupDir "$name-robocopy.log"
- robocopy $sourcePath $tempBackupDir /E /Z /COPYALL /R:3 /W:5 | Out-File -Append -FilePath $robocopyLog
- Add-Content -Path $logFile -Value "Robocopy log for $name: $robocopyLog"
- } else {
- Write-Host "`rProgress: $progressBar $($percentageComplete.ToString("F2"))% - Skipping $name: Source not found" -NoNewline
- Add-Content -Path $logFile -Value "[$(Get-Date)] Skipping $name: Source not found"
- $backupSuccess = $false
- }
- }
- Write-Host "`rProgress: [####################] 100% - Backup complete!"
- # Compress the backup into a single ZIP file
- $zipFile = Join-Path $tempBackupDir "$PlexServerName_Backup_$timestamp.zip"
- & $sevenZipPath a -tzip $zipFile $tempBackupDir\* -r
- # Move ZIP file to the destination
- if (Test-Path $zipFile) {
- Move-Item -Path $zipFile -Destination $backupDestination
- Add-Content -Path $logFile -Value "[$(Get-Date)] Backup moved to $backupDestination"
- } else {
- $backupSuccess = $false
- Add-Content -Path $logFile -Value "[$(Get-Date)] Backup failed: ZIP file not created"
- }
- # Delete temp backup files after moving the ZIP
- Remove-Item -Path $tempBackupDir\* -Recurse
- # Send success or failure email
- if ($backupSuccess) {
- $emailSubject = "[$PlexServerName] Backup Success"
- $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>"
- } else {
- $emailSubject = "[$PlexServerName] Backup Failed"
- $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>"
- }
- # Send email
- Send-Email -subject $emailSubject -body $emailBody
- # Retain log files based on retention policy
- $logFiles = Get-ChildItem -Path $logFileDir -Filter "PlexServerBackup_*.log" | Sort-Object LastWriteTime
- if ($logFiles.Count -gt $backupRetentionCount) {
- $logsToDelete = $logFiles | Select-Object -Skip $backupRetentionCount
- $logsToDelete | ForEach-Object { Remove-Item $_.FullName }
- }
- # Delete logs older than the retention period
- $oldLogs = Get-ChildItem -Path $logFileDir -Filter "PlexServerBackup_*.log" | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$logRetentionDays) }
- $oldLogs | ForEach-Object { Remove-Item $_.FullName }
- Stop-Transcript
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement