8

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

有人知道如何用 Powershell 做到这一点吗?

在此处输入图像描述

4

1 回答 1

11

假设您的登录已创建

## 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
于 2013-08-27T16:15:18.850 回答