Created
August 1, 2016 09:49
-
-
Save andykuszyk/130e2c58873bc311afd08111c973e2af to your computer and use it in GitHub Desktop.
Restoring SQL Server databases in Powershell
This file contains hidden or 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
| $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