我想使用PowerShell将现有的本地用户作为sysadmin添加到SQL Server。经过一些研究,到目前为止,我有以下脚本:
$Username = "JohnDoe" [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null $SqlServer = New-Object ('Microsoft.SqlServer.Management.Smo.Server') "localhost" $SqlUser = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Login -ArgumentList $SqlServer, "$Username" $SqlUser.LoginType = 'WindowsUser' $SqlUser.Create() $SqlUser.AddToRole('sysadmin')
该用户位于localhost上,它是Users and Administrators组的成员。我收到以下错误消息:
异常调用带有“ 0”参数的“创建”:“对于登录’JohnDoe’创建失败。”在C:\ Users \ LocalAdmin \ Desktop \ try.ps1:7 char:16 + $ SqlUser.Create <<< <()+ CategoryInfo:未指定:(:) [],MethodInvocationException + FullyQualifiedErrorId:DotNetMethodException 带有“ 1”自变量的异常调用“ AddToRole”:“登录’JohnDoe’的添加到角色失败。”在C:\ Users \ LocalAdmin \ Desktop \ try.ps1:8 char:23 + $ SqlUser.AddToRole < <<<(’sysadmin’)+ CategoryInfo:未指定:(:) [],MethodInvocationException + FullyQualifiedErrorId:DotNetMethodException
异常调用带有“ 0”参数的“创建”:“对于登录’JohnDoe’创建失败。”在C:\ Users \ LocalAdmin \ Desktop \ try.ps1:7 char:16 + $ SqlUser.Create <<< <()+ CategoryInfo:未指定:(:) [],MethodInvocationException + FullyQualifiedErrorId:DotNetMethodException
带有“ 1”自变量的异常调用“ AddToRole”:“登录’JohnDoe’的添加到角色失败。”在C:\ Users \ LocalAdmin \ Desktop \ try.ps1:8 char:23 + $ SqlUser.AddToRole < <<<(’sysadmin’)+ CategoryInfo:未指定:(:) [],MethodInvocationException + FullyQualifiedErrorId:DotNetMethodException
带有SQL Server 2008 R2的Windows Server 2008 R2我在做什么错或丢失了什么?
编辑: 根据CB和mortb的建议更新了脚本,但仍无法正常工作。我已经将上面的脚本更新为当前状态,并且错误消息中包含了我现在得到的错误消息。
我没有尝试您的代码。但是,以下示例对我的SQL Express实例很有效。
$conn = New-Object Microsoft.SqlServer.Management.Common.ServerConnection -ArgumentList $env:ComputerName $conn.applicationName = "PowerShell SMO" $conn.ServerInstance = ".\SQLEXPRESS" $conn.StatementTimeout = 0 $conn.Connect() $smo = New-Object Microsoft.SqlServer.Management.Smo.Server -ArgumentList $conn $SqlUser = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Login -ArgumentList $smo,"${env:ComputerName}\JohnDoe" $SqlUser.LoginType = 'WindowsUser' $sqlUser.PasswordPolicyEnforced = $false $SqlUser.Create()