-
Notifications
You must be signed in to change notification settings - Fork 89
/
SetupSqlUsers.ps1
50 lines (44 loc) · 1.77 KB
/
SetupSqlUsers.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
# INPUT
# $auth
# $databaseServer
# $username (optional)
# $securePassword (optional)
#
# OUTPUT
#
if ($securePassword) {
Write-Host "Setting SA Password and enabling SA"
$sqlcmd = "ALTER LOGIN sa with password='" + ([System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)).Replace('"','""').Replace('''','''''')) + "',CHECK_POLICY = OFF;ALTER LOGIN sa ENABLE;"
Invoke-SqlCmd -ServerInstance "$databaseServer\$databaseInstance" -QueryTimeout 0 -ErrorAction Stop -Query $sqlcmd
if ($auth -ne "Windows" -and $username -ne "") {
Write-Host "Creating $username as SQL User and add to sysadmin"
$sqlcmd =
"IF NOT EXISTS
(SELECT name
FROM master.sys.server_principals
WHERE name = '$username')
BEGIN
CREATE LOGIN [$username] with password='" + ([System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)).Replace('"','""').Replace('''','''''')) + "',CHECK_POLICY = OFF
EXEC sp_addsrvrolemember '$username', 'sysadmin'
END
ALTER LOGIN [$username] ENABLE
GO"
Invoke-SqlCmd -ServerInstance "$databaseServer\$databaseInstance" -QueryTimeout 0 -ErrorAction Stop -Query $sqlcmd
}
} else {
if ($auth -eq "Windows" -and $username -ne "") {
Write-Host "Adding $username to sysadmin"
$sqlcmd =
"IF NOT EXISTS
(SELECT name
FROM master.sys.server_principals
WHERE name = '$username')
BEGIN
CREATE LOGIN [$username] FROM WINDOWS
EXEC sp_addsrvrolemember '$username', 'sysadmin'
END
ALTER LOGIN [$username] ENABLE
GO"
Invoke-SqlCmd -ServerInstance "$databaseServer\$databaseInstance" -QueryTimeout 0 -ErrorAction Stop -Query $sqlcmd
}
}