-
Notifications
You must be signed in to change notification settings - Fork 4
/
Restore-Database.ps1
59 lines (56 loc) · 1.66 KB
/
Restore-Database.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#Requires -Version 2.0
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[parameter(mandatory=$true)]
[string] $server,
[parameter(mandatory=$true)]
[string] $database,
[parameter(mandatory=$true)]
[string] $username,
[parameter(mandatory=$true)]
[string] $password,
[parameter(mandatory=$true)]
[string] $backupFilePath,
[parameter(mandatory=$false)]
[hashtable] $datafilesWithMove,
[switch] $noCreate
)
$ScriptDir = $MyInvocation.MyCommand.Path | split-path
. $ScriptDir\Sql.ps1
if( ! $noCreate ) {
$SqlConnection = DbConnect $Server $null $Username $Password
try {
write-host "Creating database, please wait..."
$createDbSql = @"
CREATE DATABASE $database
ALTER DATABASE $database SET ALLOW_SNAPSHOT_ISOLATION ON
ALTER DATABASE $database SET READ_COMMITTED_SNAPSHOT ON
ALTER DATABASE $database SET COMPATIBILITY_LEVEL = 100
"@
$null = ExecuteNonQuery $SqlConnection $createDbSql
} finally {
$SqlConnection.Dispose()
}
}
Write-Host "Restoring database $database on server $server from $backupFilePath"
try
{
$SqlConnection = DbConnect $server "master" $username $password
try {
$null = ExecuteNonQuery $SqlConnection "ALTER DATABASE $database SET SINGLE_USER WITH ROLLBACK IMMEDIATE"
$restoreCommand = "RESTORE DATABASE $database FROM DISK='$backupFilePath' WITH REPLACE"
if( $datafilesWithMove ) {
$datafilesWithMove.Keys | %{
$restoreCommand += ",MOVE '$_' TO '$($datafilesWithMove[$_])'"
}
}
$null = ExecuteNonQuery $SqlConnection $restoreCommand
$null = ExecuteNonQuery $SqlConnection "ALTER DATABASE $database SET MULTI_USER"
} finally {
$SqlConnection.Dispose()
}
}
catch
{
throw "Database restore failed! $_"
}