Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell - User Mapping SQL Server 2012

I am trying to script User Mapping for different Login accounts. I have scripted the creation of users and individual server roles, but I can't figure out how to set User Mapping with Powershell, I will also need to set the Database Role membership, in Particular, db_backupoperator

Anyone know how to do this with Powershell?

enter image description here

like image 810
JMeterX Avatar asked Aug 27 '13 14:08

JMeterX


1 Answers

Supposing your login is created

## Creating database user and assigning database role    

#get variables
$instanceName = "yourInstance"
$loginName = "testLogin"
$dbUserName = "testUserName"
$databasename = "tempdb"
$roleName = "db_backupoperator"
$server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName

#add a database mapping
$database = $server.Databases[$databasename]
$login = $server.Logins[$loginName]
if ($database.Users[$dbUserName])
{
    $database.Users[$dbUserName].Drop()
}
$dbUser = New-Object `
-TypeName Microsoft.SqlServer.Management.Smo.User `
-ArgumentList $database, $dbUserName
$dbUser.Login = $loginName
$dbUser.Create()

#assign database role for a new user
$dbrole = $database.Roles[$roleName]
$dbrole.AddMember($dbUserName)
$dbrole.Alter
like image 107
Aleksandr Fedorenko Avatar answered Nov 08 '22 16:11

Aleksandr Fedorenko