2016-05-18 111 views
1

當我嘗試將新的登錄名添加到我的SQL服務器時,總是會出現此錯誤。 我在網上搜索它,我發現這在StackOverflow Add Windows User to local SQL Server with PowerShell但這並沒有解決它。嘗試創建新的SQL帳戶時發生異常

這是錯誤

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.") 
} 
+1

是否SQL實例有更多的細節至於爲什麼失敗?也許有密碼限制。您是否有權創建這些帳戶? – Matt

+1

不,那是我得到的唯一錯誤 – achahbar

+0

您確定該用戶尚未從遷移任務或測試中創建? http://www.beansoftware.com/T-SQL-FAQ/create-failed-for-user.aspx。您的if語句仍然可以評估爲null以觸發該子句。由於我們沒有看到'$ svr'聲明我想確定。 – Matt

回答

1

@馬特這是孔腳本 ,因爲它給了我更多的錯誤的誰是極爲相象我顯示我的問題錯誤我只是集中在那個錯誤

$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 " 
    } 
相關問題