Skip to content

Instantly share code, notes, and snippets.

@dfar-io
Created May 28, 2020 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfar-io/7282b9f58537f176c0552f7fd3934fae to your computer and use it in GitHub Desktop.
Save dfar-io/7282b9f58537f176c0552f7fd3934fae to your computer and use it in GitHub Desktop.
Copies a SQL Server database with a different name.
<#
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 ([string]::IsNullOrEmpty($restoreDbName) -eq $false -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