Powershell - 用户映射SQL Server 2012

时间:2013-08-27 14:44:30

标签: sql sql-server powershell sql-server-2012 sqlps

我正在尝试为不同的登录帐户编写用户映射脚本。我编写了用户和单个服务器角色的创建脚本,但我无法弄清楚如何使用Powershell设置用户映射,我还需要设置Database Role membership,特别是db_backupoperator

任何人都知道如何使用Powershell做到这一点?

enter image description here

1 个答案:

答案 0 :(得分:9)

假设您的登录已创建

## 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