Skip to content

Instantly share code, notes, and snippets.

@andykuszyk
Created August 1, 2016 09:49
Show Gist options
  • Select an option

  • Save andykuszyk/130e2c58873bc311afd08111c973e2af to your computer and use it in GitHub Desktop.

Select an option

Save andykuszyk/130e2c58873bc311afd08111c973e2af to your computer and use it in GitHub Desktop.
Restoring SQL Server databases in Powershell
$dbName = "MyDatabase"
$serverAddress = ".\SqlServer"
# Delete the existing database.
$server = new-Object Microsoft.SqlServer.Management.Smo.Server($serverAddress)
if($server.Databases[$dbName)
{
$server.KillDatabase($dbName)
}
# Prepare new locations for the database files to live.
$RelocateData = `
New-Object 'Microsoft.SqlServer.Management.Smo.RelocateFile, Microsoft.SqlServer.SmoExtended, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' `
-ArgumentList $dbName,"path\to\data\$dbName.mdf"
$RelocateLog = `
New-Object 'Microsoft.SqlServer.Management.Smo.RelocateFile, Microsoft.SqlServer.SmoExtended, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' `
-ArgumentList "$dbName_log","path\to\data\$dbName.ldf"
Restore-SqlDatabase `
-ServerInstance $serverAddress`
-Database $dbName `
-BackupFile "Path\to\backup.bak" `
-RestoreAction Database `
-RelocateFile @($RelocateData,$RelocateLog)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment