56 lines
2.1 KiB
PowerShell
56 lines
2.1 KiB
PowerShell
|
function Add-LocalServiceAccountsToAlkamiDatabase {
|
||
|
[CmdletBinding()]
|
||
|
param (
|
||
|
[string]$connectionString,
|
||
|
[string]$databaseName
|
||
|
)
|
||
|
|
||
|
$logLead = Get-LogLeadName
|
||
|
|
||
|
Confirm-DatabaseAccess $connectionString
|
||
|
|
||
|
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection $connectionString
|
||
|
|
||
|
$sqlConnection.Open()
|
||
|
|
||
|
[System.Data.SqlClient.SqlCommand]$command = $sqlConnection.CreateCommand()
|
||
|
$command.CommandText = "select [name] from [sys].[database_principals] where [type]='u' and [name]!='dbo';"
|
||
|
[System.Data.SqlClient.SqlDataReader]$reader = $command.ExecuteReader()
|
||
|
$dbNames = @()
|
||
|
while ($reader.Read()) {
|
||
|
$dbNames += $reader[0].ToString()
|
||
|
}
|
||
|
$reader.Dispose()
|
||
|
|
||
|
$isMaster = ($databaseName -match 'AlkamiMaster')
|
||
|
|
||
|
foreach ($account in (Get-SDKUserMatrix)) {
|
||
|
# This is already set in the UserMatrix to either be on the domain or use the local account info
|
||
|
$username = $account.DomainUsername.Trim()
|
||
|
# this is for the local database, not the server
|
||
|
$role = $account.DbRole
|
||
|
if (!$isMaster -or ($isMaster -and $account.IsMaster)) {
|
||
|
Write-Host "$logLead : Applying changes to $username on $databaseName"
|
||
|
$commandTexts = @()
|
||
|
if (!$dbNames.Contains($username)) {
|
||
|
$commandTexts += "CREATE USER [$username] FOR LOGIN [$username]"
|
||
|
}
|
||
|
$commandTexts += "ALTER USER [$username] WITH DEFAULT_SCHEMA=[dbo]"
|
||
|
$commandTexts += "ALTER ROLE [$role] ADD MEMBER [$username];"
|
||
|
foreach ($commandText in $commandTexts) {
|
||
|
try {
|
||
|
[System.Data.SqlClient.SqlCommand]$command = $sqlConnection.CreateCommand()
|
||
|
Write-Host $commandText
|
||
|
$command.CommandText = $commandText
|
||
|
$command.ExecuteNonQuery() | Out-Null
|
||
|
} catch {
|
||
|
Write-Warning $_.Exception.Message
|
||
|
}
|
||
|
}
|
||
|
} else {
|
||
|
Write-Debug "$logLead : Database does not pertain to this user [$username]"
|
||
|
}
|
||
|
}
|
||
|
|
||
|
$sqlConnection.Close()
|
||
|
}
|