![]() |
Advanced File Backup with Compression and Email Notification PowerShell - Printable Version +- Sinisterly (https://sinister.ly) +-- Forum: Coding (https://sinister.ly/Forum-Coding) +--- Forum: Coding (https://sinister.ly/Forum-Coding--71) +--- Thread: Advanced File Backup with Compression and Email Notification PowerShell (/Thread-Advanced-File-Backup-with-Compression-and-Email-Notification-PowerShell) |
Advanced File Backup with Compression and Email Notification PowerShell - vluzzy - 01-02-2024 # Advanced Backup Script with Compression and Email Notification # Configuration $sourceFolder = "C:\Source" $destinationFolder = "C:\Backup" $zipFileName = "Backup_$(Get-Date -Format 'yyyyMMdd_HHmmss').zip" $zipFilePath = Join-Path $destinationFolder $zipFileName $logFilePath = "C:\Backup\backup_log.txt" $recipientEmail = "your.email@example.com" $smtpServer = "smtp.example.com" $smtpFrom = "backup@example.com" $smtpSubjectSuccess = "Backup Successful" $smtpSubjectFailure = "Backup Failed" # Logging function function Log($message) { $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm ![]() Add-Content -Path $logFilePath -Value "$timestamp - $message" } # Backup files try { Log "Starting backup of files from $sourceFolder to $zipFilePath" if (-not (Test-Path $destinationFolder)) { New-Item -ItemType Directory -Force -Path $destinationFolder | Out-Null } Compress-Archive -Path $sourceFolder -DestinationPath $zipFilePath -Force Log "Backup completed successfully." # Send email notification $smtpBody = "Backup completed successfully. Attached is the backup file." Send-MailMessage -To $recipientEmail -From $smtpFrom -Subject $smtpSubjectSuccess -Body $smtpBody -Attachments $zipFilePath -SmtpServer $smtpServer } catch { # Handle errors $errorMessage = $_.Exception.Message Log "Error during backup: $errorMessage" # Send email notification for failure $smtpBodyFailure = "Backup failed with the following error: $errorMessage" Send-MailMessage -To $recipientEmail -From $smtpFrom -Subject $smtpSubjectFailure -Body $smtpBodyFailure -SmtpServer $smtpServer } # End of script Explanation: The script sets configuration parameters such as source and destination folders, file names, email details, etc. It uses the Compress-Archive cmdlet to create a zip archive of the files. Logging is performed using a custom function Log. The script handles errors gracefully and sends an email notification in case of failure. It uses the Send-MailMessage cmdlet to send email notifications with or without attachments. |