-
Notifications
You must be signed in to change notification settings - Fork 4
/
ReCreate-SqlUser.ps1
62 lines (58 loc) · 1.52 KB
/
ReCreate-SqlUser.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
param(
[parameter(mandatory=$true)]
[string] $server,
[parameter(mandatory=$true)]
[string] $database,
[string] $username,
[string] $password,
[string[]] $readers,
[string[]] $writers,
[string[]] $owners,
[string] $defaultSchema = 'dbo',
[switch] $force
)
$ScriptDir = $MyInvocation.MyCommand.Path | split-path
. $ScriptDir\Sql.ps1
$rolemap = @{}
function addRoleMap( $user, $role ) {
if( !$rolemap.ContainsKey( $user ) ) {
$rolemap.Add( $user, @( $role ) )
} elseif( $rolemap[$user] -notcontains $role ) {
$rolemap[$user] = $rolemap[$user] + $role
}
}
$readers | ?{ $_ -ne $null } | %{ addRoleMap $_ 'db_datareader' }
$writers | ?{ $_ -ne $null } | %{ addRoleMap $_ 'db_datawriter' }
$owners | ?{ $_ -ne $null } | %{ addRoleMap $_ 'db_owner' }
$Sql = ""
$rolemap.Keys | %{
$userKey = $_
$Sql += @"
USE [$Database]
GO
IF EXISTS (SELECT * FROM sys.database_principals WHERE name = N'$userKey')
DROP USER [$userKey]
GO
USE [$Database]
GO
CREATE USER [$userKey] FOR LOGIN [$userKey] WITH DEFAULT_SCHEMA=[$defaultSchema]
GO`r`n
"@
$rolemap[$userKey] | %{ $Sql += "EXEC sp_addrolemember N'$_', N'$userKey'`r`nGO`r`n" }
}
Write-Host "Generated SQL:"
$Sql | oh
if($force ) {
Write-Host "Executing command..."
try {
$SqlConnection = DbConnect $Server $Database $Username $Password
$null = ExecuteScript $SqlConnection $Sql
Write-Host "Done."
} finally {
if( $SqlConnection -ne $null ) {
$SqlConnection.Dispose()
}
}
} else {
Write-Host "You must specify -Force to actually send the command to the SQL server"
}