← script library
Effortlessly Backup SQL Server Databases with PowerShell
Backup & RecoveryDecember 24, 2024
In this post, we will present a PowerShell script that automates the backup process of SQL Server databases. Regular backups are essential for data protection and recovery in case of failures. This script allows database administrators to back up specified databases to a designated location easily, ensuring that critical data is always safeguarded. Here is the PowerShell script for backing up SQL Server databases:
powershell
# Define SQL Server instance and database details
$serverInstance = "localhost" # Replace with your SQL Server instance name
$databaseName = "YourDatabase" # Replace with the name of the database to backup
$backupDirectory = "C:\Backups" # Replace with your preferred backup directory
# Formulate the backup file name
$backupFile = "$backupDirectory\$databaseName-$((Get-Date).ToString('yyyyMMddHHmmss')).bak"
# Backup the database
Invoke-Sqlcmd -Query "BACKUP DATABASE [$databaseName] TO DISK='$backupFile' WITH INIT, SKIP, NOREWIND, NOUNLOAD, STATS=10" -ServerInstance $serverInstance
Write-Host "Database backup completed successfully for $databaseName. Backup file location: $backupFile"Run it across your fleet
This script runs as-is on a single host. Paste it into ServerEngine to schedule it, run it on a whole server group in parallel, and keep the credentials out of the file — see the scripts documentation and the credential store.
Ready when you are.
Try ServerEngine free for 7 days.