sript make mssql backup, arhive, copy to directory everyday, copy to another derictory…
- User
sript make mssql backup, arhive, copy to directory everyday, copy to another derictory one in week, copy to another deryctory one in moth
Assistant
sript make mssql backup, arhive, copy to directory everyday, copy to another derictory one in week, copy to another deryctory one in moth
Of course. Here is a comprehensive PowerShell script that accomplishes all your requirements. This script is robust, includes logging, error handling, and a cleanup mechanism to prevent your disks from filling up.
.zip archive to save space.Save the following code as a file named Run-SqlBackup.ps1.
<#
.SYNOPSIS
A PowerShell script to perform a full backup of an MS SQL Server database.
It creates the backup, zips it, and copies it to daily, weekly, and monthly
retention folders based on the current date. It also cleans up old backups.
.DESCRIPTION
1. Backs up a specified SQL database to a temporary location.
2. Compresses the .bak file into a .zip archive.
3. Copies the .zip archive to a daily backup folder.
4. If it's the specified day of the week, copies the archive to the weekly folder.
5. If it's the specified day of the month, copies the archive to the monthly folder.
6. Cleans up the initial temporary .bak and .zip files.
7. Cleans up old backups in the daily, weekly, and monthly folders based on retention settings.
8. Logs all actions to a transcript file.
.AUTHOR
Generated by an AI Assistant for your use.
.NOTES
Prerequisites:
- PowerShell 5.1 or later.
- The 'SqlServer' PowerShell module must be installed. Run: Install-Module -Name SqlServer
- The user account running this script needs:
- db_backupoperator (or higher) role on the SQL database.
- Read/Write/Delete permissions on the specified backup and log directories.
#>
#region ----------------- CONFIGURATION - EDIT THESE VALUES -----------------
# --- SQL Server Settings ---
$sqlInstance = "YOUR_SERVER_NAME\YOUR_INSTANCE_NAME" # e.g., "localhost\SQLEXPRESS" or "PROD_SQL_SERVER"
$databaseName = "YourDatabaseName" # The name of the database to back up
# --- Directory Paths (Make sure these folders exist!) ---
# A temporary working directory for creating the initial files.
$workingPath = "C:\SQL_Backups\_temp"
# Destination directories for the backups.
$dailyPath = "D:\SQL_Backups\Daily"
$weeklyPath = "E:\SQL_Backups_Archive\Weekly"
$monthlyPath = "F:\SQL_Backups_Archive\Monthly"
$logPath = "C:\SQL_Backups\_logs"
# --- Scheduling Rules ---
# Day of the week for the weekly copy. Options: Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
$weeklyDay = "Sunday"
# Day of the month for the monthly copy (1-31). The script will run on the 1st of every month.
$monthlyDay = 1
# --- Retention Policy (in days) ---
# How many days of backups to keep in each directory.
$retentionDaily = 7 # Keep 7 days of daily backups
$retentionWeekly = 35 # Keep 5 weeks of weekly backups
$retentionMonthly = 366 # Keep 1 year of monthly backups
#endregion ----------------- END OF CONFIGURATION -----------------
#region ----------------- HELPER FUNCTIONS -----------------
function Clean-OldBackups {
param(
[string]$Path,
[int]$RetentionDays
)
Write-Host "--- Cleaning up old backups in '$Path' (older than $RetentionDays days) ---"
try {
$limit = (Get-Date).AddDays(-$RetentionDays)
$oldFiles = Get-ChildItem -Path $Path -File | Where-Object { $_.LastWriteTime -lt $limit }
if ($oldFiles) {
foreach ($file in $oldFiles) {
Write-Host "Deleting old backup: $($file.FullName)"
Remove-Item -Path $file.FullName -Force
}
} else {
Write-Host "No old backups found to clean up in this directory."
}
}
catch {
Write-Error "Failed to clean up old backups in '$Path'. Error: $_"
}
Write-Host "--- Cleanup for '$Path' finished. ---"
}
#endregion
#region ----------------- MAIN SCRIPT LOGIC -----------------
# --- Prepare for Execution ---
# Generate a timestamp for unique filenames
$timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
$backupFileName = "$($databaseName)_$($timestamp).bak"
$zipFileName = "$($databaseName)_$($timestamp).zip"
# Full paths for the temporary files
$bakFilePath = Join-Path -Path $workingPath -ChildPath $backupFileName
$zipFilePath = Join-Path -Path $workingPath -ChildPath $zipFileName
# Create directories if they don't exist
$pathsToCreate = @($workingPath, $dailyPath, $weeklyPath, $monthlyPath, $logPath)
foreach ($path in $pathsToCreate) {
if (-not (Test-Path -Path $path)) {
Write-Host "Creating directory: $path"
New-Item -ItemType Directory -Path $path | Out-Null
}
}
# --- Start Logging ---
$logFile = Join-Path -Path $logPath -ChildPath "BackupLog_$($timestamp).log"
Start-Transcript -Path $logFile -Append
Write-Host "============================================================"
Write-Host "Starting SQL Backup Process for database '$databaseName'"
Write-Host "Script started at $(Get-Date)"
Write-Host "============================================================"
try {
# Step 1: Perform the SQL Backup
Write-Host "Step 1: Backing up database '$databaseName' to '$bakFilePath'..."
# Using SQL Server's own compression for the .bak file
Backup-SqlDatabase -ServerInstance $sqlInstance -Database $databaseName -BackupFile $bakFilePath -BackupAction Database -CompressionOption On -ConnectionTimeout 600
Write-Host "Database backup completed successfully."
# Step 2: Archive the Backup File
Write-Host "Step 2: Compressing '$bakFilePath' to '$zipFilePath'..."
Compress-Archive -Path $bakFilePath -DestinationPath $zipFilePath -CompressionLevel Optimal
Write-Host "Compression completed successfully."
# Step 3: Copy to Daily Directory
Write-Host "Step 3: Copying backup to Daily directory: '$dailyPath'..."
Copy-Item -Path $zipFilePath -Destination $dailyPath -Force
Write-Host "Daily copy completed."
# Step 4: Conditional Copy to Weekly Directory
if ((Get-Date).DayOfWeek -eq $weeklyDay) {
Write-Host "Step 4: It's $weeklyDay! Copying backup to Weekly directory: '$weeklyPath'..."
Copy-Item -Path $zipFilePath -Destination $weeklyPath -Force
Write-Host "Weekly copy completed."
}
else {
Write-Host "Step 4: Skipping weekly copy. Today is not $weeklyDay."
}
# Step 5: Conditional Copy to Monthly Directory
if ((Get-Date).Day -eq $monthlyDay) {
Write-Host "Step 5: It's the $($monthlyDay)st/th of the month! Copying backup to Monthly directory: '$monthlyPath'..."
Copy-Item -Path $zipFilePath -Destination $monthlyPath -Force
Write-Host "Monthly copy completed."
}
else {
Write-Host "Step 5: Skipping monthly copy. Today is not day $monthlyDay of the month."
}
# Step 6: Cleanup Temporary Files
Write-Host "Step 6: Cleaning up temporary files from '$workingPath'..."
Remove-Item -Path $bakFilePath -Force
Remove-Item -Path $zipFilePath -Force
Write-Host "Temporary files cleaned up."
# Step 7: Cleanup Old Backups (Retention Policy)
Write-Host "Step 7: Enforcing retention policies..."
Clean-OldBackups -Path $dailyPath -RetentionDays $retentionDaily
Clean-OldBackups -Path $weeklyPath -RetentionDays $retentionWeekly
Clean-OldBackups -Path $monthlyPath -RetentionDays $retentionMonthly
Write-Host "Retention policy enforcement completed."
Write-Host "============================================================"
Write-Host "Backup process finished successfully at $(Get-Date)."
Write-Host "============================================================"
}
catch {
# If any error occurs in the 'try' block, this will run
$errorMessage = "FATAL ERROR: The backup process failed. Error: $($_.Exception.Message)"
Write-Error $errorMessage
Write-Host "============================================================"
# Exit with a non-zero code to indicate failure to task schedulers
exit 1
}
finally {
# This block runs whether the script succeeded or failed
Stop-Transcript
}
#endregion
Install the SqlServer Module: If you haven't already, open PowerShell as an Administrator and run this command:
Install-Module -Name SqlServer -Scope AllUsers -Force
Answer Y (Yes) or A (Yes to All) to any prompts about trusted repositories.
Permissions: Ensure the user account that will run this script has:
db_backupoperator role (or db_owner / sysadmin) on the SQL database you are backing up.$workingPath, $dailyPath, etc.).Run-SqlBackup.ps1 file in a text editor (like VS Code, PowerShell ISE, or even Notepad).Before automating, run the script once manually to make sure everything works.
cd C:\Scripts)..\Run-SqlBackup.ps1$logPath directory. Verify that the backup file appears in the $dailyPath.This is how you make the script run every day automatically.
Open Task Scheduler from the Windows Start Menu.
In the right-hand Actions pane, click Create Task... (do not use "Create Basic Task" as it offers fewer options).
General Tab:
SQL Daily Backup - YourDatabaseName.Triggers Tab:
On a schedule.2:00 AM).Actions Tab:
Start a program.powershell.exe-NoProfile -ExecutionPolicy Bypass -File "C:\Path\To\Your\Run-SqlBackup.ps1"
"C:\Path\To\Your\Run-SqlBackup.ps1" with the actual full path to your script.-ExecutionPolicy Bypass ensures the script can run even if your system's execution policy is restrictive.Settings Tab:
2 hours.Do not start a new instance.Click OK to save the task. You will be prompted to enter the password for the user account you selected to run the task.
Your automated, tiered backup system is now complete. It will run every day at the scheduled time, handling all the logic for you.