Created
May 28, 2020 18:41
-
-
Save dfar-io/7282b9f58537f176c0552f7fd3934fae to your computer and use it in GitHub Desktop.
Copies a SQL Server database with a different name.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
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