-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstart.ps1
74 lines (58 loc) · 2.15 KB
/
start.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
param(
[Parameter(Mandatory=$false)]
[string]$sa_password,
[Parameter(Mandatory=$false)]
[string]$attach_dbs,
[Parameter(Mandatory=$false)]
[string]$restore_dbs
)
Write-Verbose "Starting SQL Server"
start-service MSSQLSERVER
if(!$sa_password) {
Write-Verbose "ERROR: No password for user 'sa' provided"
exit 1
}
else
{
Write-Verbose "Changing SA login credentials"
$sqlcmd = "ALTER LOGIN sa with password=" +"'" + $sa_password + "'" + ";ALTER LOGIN sa ENABLE;"
& sqlcmd -Q $sqlcmd
}
$attach_dbs_cleaned = $attach_dbs.TrimStart('\\').TrimEnd('\\')
$attach_dbs_Json = $attach_dbs_cleaned | ConvertFrom-Json
if ($null -ne $attach_dbs_Json -And $attach_dbs_Json.Length -gt 0)
{
Write-Verbose "Attaching $($attach_dbs_Json.Length) database(s)"
Foreach($db in $attach_dbs_Json)
{
$files = @();
Foreach($file in $db.dbFiles)
{
$files += "(FILENAME = N'$($file)')";
}
$files = $files -join ","
$sqlcmd = "IF EXISTS (SELECT 1 FROM SYS.DATABASES WHERE NAME = '" + $($db.dbName) + "') BEGIN EXEC sp_detach_db [$($db.dbName)] END;CREATE DATABASE [$($db.dbName)] ON $($files) FOR ATTACH;"
Write-Verbose "Invoke-Sqlcmd -Query $($sqlcmd)"
& sqlcmd -Q $sqlcmd
}
}
$restore_dbs_cleaned = $restore_dbs.TrimStart('\\').TrimEnd('\\')
$restore_dbs_Json = $restore_dbs_cleaned | ConvertFrom-Json
if ($null -ne $restore_dbs_Json -And $restore_dbs_Json.Length -gt 0)
{
Write-Verbose "Restoring $($restore_dbs_Json.Length) database(s)"
Foreach($db in $restore_dbs_Json)
{
$parameters = @("backup=" + $db.dbBackup + "") + @("databaseName=" + $db.dbName + "") + @("databaseLocation=" + $db.dbLocation + "")
Write-Host "Parameters for restore:" $parameters
Invoke-Sqlcmd -InputFile "restore.sql" -Variable $parameters
}
}
Write-Verbose "Started SQL Server."
$lastCheck = (Get-Date).AddSeconds(-2)
while ($true)
{
Get-EventLog -LogName Application -Source "MSSQL*" -After $lastCheck | Select-Object TimeGenerated, EntryType, Message
$lastCheck = Get-Date
Start-Sleep -Seconds 2
}