当我尝试将新登录添加到我的SQL服务器时,我总是收到此错误。 我在网上搜索了一下,我在StackOverflow上找到了它 Add Windows User to local SQL Server with PowerShell但这并没有解决它。
这是错误
Exception calling "Create" with "1" argument(s): "Create failed for Login 'bilal'. "
这是我的代码
$server="WIN-SH7H3HP7KMI\SQL2014"
$User="bilal"
$password="test"
if(!($svr.Logins.Contains($User)))
{
$login = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Login -ArgumentList $server, $User
$login.LoginType = [Microsoft.SqlServer.Management.Smo.LoginType]::SqlLogin
$login.PasswordExpirationEnabled = $false
$login.Create($password)
Write-Host("Login $loginName created successfully.")
}
答案 0 :(得分:1)
@Matt这是洞脚本 因为它给了我更多的错误,这些错误与我在问题中显示的错误相似,我只关注那个错误
$server="WIN-SH7H3HP7KMI\SQL2014"
$Database="master"
$User="bilal"
$Role="db_owner"
$Svr = New-Object ('Microsoft.SqlServer.Management.Smo.Server') $server
# create new database and add to server
# [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO')
#$srv=new-Object Microsoft.SqlServer.Management.Smo.Server('(local)\Test')
#$db=New-Object Microsoft.SqlServer.Management.Smo.Database($srv,'Test_SMO_Database')
#$db.Create()
#Check Database Name entered correctly
$db = $svr.Databases[$Database]
if($db -eq $null)
{
Write-Host " $Database is not a valid database on $Server"
Write-Host " Databases on $Server are :"
$svr.Databases|select name
break
}
#Check Role exists on Database
$Rol = $db.Roles[$Role]
if($Rol -eq $null)
{
Write-Host " $Role is not a valid Role on $Database on $Server "
Write-Host " Roles on $Database are:"
$db.roles|select name
break
}
if(!($svr.Logins.Contains($User)))
{
$password="test"
$login = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Login -ArgumentList $server, $User
$login.LoginType = [Microsoft.SqlServer.Management.Smo.LoginType]::SqlLogin
$login.PasswordExpirationEnabled = $false
$login.Create($password)
Write-Host("Login $loginName created successfully.")
}
if (!($db.Users.Contains($User)))
{
# Add user to database
$usr = New-Object ('Microsoft.SqlServer.Management.Smo.User') ($db, $User)
$usr.Login = $User
$usr.Create()
#Add User to the Role
$Rol = $db.Roles[$Role]
$Rol.AddMember($User)
Write-Host "$User was not a login on $Database on $server"
Write-Host "$User added to $Database on $Server and $Role Role"
}
else
{
#Add User to the Role
$Rol = $db.Roles[$Role]
$Rol.AddMember($User)
Write-Host "$User added to $Role Role in $Database on $Server "
}