Skip to content

Instantly share code, notes, and snippets.

@dfar-io
Created September 3, 2024 12:43
Show Gist options
  • Save dfar-io/fa2ba0ca473153c946f6cc228339f910 to your computer and use it in GitHub Desktop.
Save dfar-io/fa2ba0ca473153c946f6cc228339f910 to your computer and use it in GitHub Desktop.
<#
Backs up and optionally restores a SQL Server database.
#>
param (
[Parameter(Mandatory, Position=0)][string]$backupDbName,
[Parameter(Position=1)][string]$restoreDbName
)
$timestamp = $(((get-date).ToUniversalTime()).ToString("yyyyMMddTHHmmssZ"));
$filename = "${backupDbName}_$timestamp.bak"
# backs up database
SQLCMD -S SQLSERVER -U sa -P '""' -Q "BACKUP DATABASE $backupDbName TO DISK='C:\SqlBackups\$filename'"
# restores backed up database to a different database
if ($restoreDbName -ne $null -and $restoreDbName -ne $backupDbName)
{
SQLCMD -S SQLSERVER -U sa -P '""' `
-Q "RESTORE DATABASE $restoreDbName FROM DISK='C:\SqlBackups\$filename' `
WITH MOVE 'NOPCommerce_Sample' to 'C:\SqlFiles\Data\$restoreDbName.mdf', `
MOVE 'NOPCommerce_Sample_log' TO 'C:\SqlFiles\Log\$restoreDbName.ldf'"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment