Project

General

Profile

Feature #6 » backupsqlserver.ps1

Sam Bracewell, 05/01/2026 01:22 PM

 
# Script to backup MS SQL Server
# Folders permissions may need to be adjusted
# `n = newline character



$pc = get-content env:computername
$Report = "OK"
$attach=""

try {

$Folder = "C:\Users\Administrator\Documents\Backups\SQLEXPRESS2022"
$LogFolder = "C:\Users\Administrator\Documents\Logs"

# Create folder if does not exist

if (!(Test-Path $Folder -PathType Container)) {
New-Item -ItemType Directory -Force -Path $Folder
}


if (!(Test-Path $LogFolder -PathType Container)) {
New-Item -ItemType Directory -Force -Path $LogFolder
}

# Backup MS SQL Server all databases
Get-ChildItem "SQLSERVER:\SQL\WIN-9F9GF20AF5E\SQLEXPRESS2022\Databases" | Backup-SqlDatabase -BackupContainer "$($Folder)\"

#Compress-Archive -Path "$($Folder)\*" -Update -DestinationPath "$($Folder)\SQLEXPRESS2022 Backups.zip"

# Compress all backup files into a Zip file
$file=Get-ChildItem -Path "$($Folder)\*" -Exclude "*.zip"
$compress = @{
Path = $file
CompressionLevel = "Optimal" # Optimal, NoCompression, Fastest
DestinationPath = "$($Folder)\SQLEXPRESS2022 Backups.zip"
}
Compress-Archive @compress -Force

$attach="$($Folder)\SQLEXPRESS2022 Backups.zip"

# Delete all the backup files except for the Zip
$fielsToDelete= @{
Path = $file
}
Remove-Item @fielsToDelete

}
catch
{
Write-Host $_
$Report = $_
}
finally
{




$body = $Report
$from = "reportnotify@kids-avenue.co.uk"
$to = "sam@scandinavianhouse.co.uk"
$pc = get-content env:computername
$subject = "SQL Server Backup" + " " + $pc
$smtpserver ="mail.kids-avenue.co.uk"
#$body = $_
$secpasswd = ConvertTo-SecureString "P:**sionL:st1" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("reportnotify@kids-avenue.co.uk", $secpasswd)


Send-MailMessage -SmtpServer $smtpserver -Port 587 -Credential $cred -UseSsl -From $from -To $to -Subject $subject -Body $body -Attachments $attach
}



#Delete files older than x months
#Get-ChildItem $Folder -Recurse -Force -ea 0 |
#? {!$_.PsIsContainer -and $_.LastWriteTime -lt (Get-Date).AddMinutes(-180)} |
#ForEach-Object {
# $_ | del -Force
# $_.FullName | Out-File "$($LogFolder)\deletedlog.txt" -Append
#}
    (1-1/1)