我想使用 PowerShell 将现有本地用户作为系统管理员添加到 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')
该用户存在于本地主机上,它是用户组和管理员组的成员。我收到以下错误消息:
使用“0”个参数调用“Create”时发生异常:“创建失败”
登录“JohnDoe”。 “位于 C:\Users\LocalAdmin\Desktop\try.ps1:7 字符:16
+ $SqlUser.Create
使用“1”个参数调用“AddToRole”时出现异常:“添加到角色
登录“JohnDoe”失败。 “位于 C:\Users\LocalAdmin\Desktop\try.ps1:8
字符:23
+ $SqlUser.AddToRole
Windows Server 2008 R2 与 SQL Server 2008 R2
我做错了什么或者我错过了什么?
EDIT:根据 C.B. 和 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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)