-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathadd_user_to_db.ps1
41 lines (36 loc) · 1.11 KB
/
add_user_to_db.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
function add_user_to_db
{
param (
[String] $inst = $null,
[String] $loginName = $null,
[String] $dbName = $null
)
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null
if($sqlServer -eq $null) {
try {
$sqlServer = New-Object ('Microsoft.SqlServer.Management.SMO.Server') $inst
} catch [Exception] {
$error[0] | format-list -force
}
}
$ourLogin = $sqlServer.Logins[$loginName]
$ourDatabase = $sqlServer.Databases[$dbName]
if($ourDatabase -eq $null) {
Write-Host 'Database not found'
Exit 1
}
if($ourLogin -eq $null) {
Write-Host 'Login not found'
Exit 1
}
$user = $ourDatabase.Users[$loginName]
if($user -eq $null) {
Write-Host "Adding $loginName to $dbName"
$user = New-Object -TypeName Microsoft.SqlServer.Management.Smo.User `
-ArgumentList $ourDatabase, $loginName
$user.Login = $loginName
$user.Create()
} else {
Write-Host "$loginName already mapped to $dbName"
}
}