forked from Azure/azure-quickstart-templates
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAddDatabaseToSqlServer.ps1
59 lines (51 loc) · 1.73 KB
/
AddDatabaseToSqlServer.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
param(
[string]
$userName,
[string]
$password
)
if ((Get-Command Install-PackageProvider -ErrorAction Ignore) -eq $null)
{
# Load the latest SQL PowerShell Provider
(Get-Module -ListAvailable SQLPS `
| Sort-Object -Descending -Property Version)[0] `
| Import-Module;
}
else
{
# Conflicts with SqlServer module
Remove-Module -Name SQLPS -ErrorAction Ignore;
if ((Get-Module -ListAvailable SqlServer) -eq $null)
{
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force | Out-Null;
Install-Module -Name SqlServer -Force -AllowClobber | Out-Null;
}
# Load the latest SQL PowerShell Provider
Import-Module -Name SqlServer;
}
$fileList = Invoke-Sqlcmd `
-QueryTimeout 0 `
-ServerInstance . `
-UserName $username `
-Password $password `
-Query "restore filelistonly from disk='$($pwd)\AdventureWorks2016.bak'";
# Create move records for each file in the backup
$relocateFiles = @();
foreach ($nextBackupFile in $fileList)
{
# Move the file to the default data directory of the default instance
$nextBackupFileName = Split-Path -Path ($nextBackupFile.PhysicalName) -Leaf;
$relocateFiles += New-Object `
Microsoft.SqlServer.Management.Smo.RelocateFile( `
$nextBackupFile.LogicalName,
"$env:temp\$($nextBackupFileName)");
}
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credentials = New-Object System.Management.Automation.PSCredential ($username, $securePassword)
Restore-SqlDatabase `
-ReplaceDatabase `
-ServerInstance . `
-Database "SampleDatabase" `
-BackupFile "$pwd\AdventureWorks2016.bak" `
-RelocateFile $relocateFiles `
-Credential $credentials;