1

我想使用 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”参数调用“创建”的异常:“登录 'JohnDoe' 创建失败。”在 C:\Users\LocalAdmin\Desktop\try.ps1:7 char:16 + $SqlUser.Create <<< < () + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : DotNetMethodException

使用“1”参数调用“AddToRole”的异常:“登录 'JohnDoe' 添加到角色失败。”在 C:\Users\LocalAdmin\Desktop\try.ps1:8 char:23 + $SqlUser.AddToRole < <<< ('sysadmin') + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : DotNetMethodException

Windows Server 2008 R2 和 SQL Server 2008 R2 我做错了什么或者我错过了什么?

编辑:根据 CB 和 mortb 的建议更新了脚本,但仍然无法正常工作。我已将上面的脚本更新为当前状态,以及我现在得到的错误消息。

4

4 回答 4

5

我没有尝试你的代码。但是,以下一个在我的 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()
于 2013-05-17T14:04:42.063 回答
1

改变

'$Username'

"$Username"

请注意,在 powershell 变量中,不会以单引号扩展,然后 '$Username' 被视为文字,而不是变量的值。

于 2013-05-17T13:33:43.163 回答
0
function SQL-Get-Server-Instance
{
    param (
        [parameter(Mandatory = $true)][string] $DatabaseServer,
        [parameter(Mandatory = $true)][string] $InstanceName
    )

    if (!$InstanceName -or $InstanceName -eq "" -or $InstanceName -eq "MSSQLSERVER")
        { return $DatabaseServer }
    else
        { return "$DatabaseServer\$InstanceName" }
}


function Create-SQL-Login
{
    param (
        [parameter(Mandatory = $true)][string] $loginName,
        [parameter(Mandatory = $true)][string] $DatabaseServer,
        [parameter(Mandatory = $false)][string] $InstanceName = "MSSQLSERVER"
    )

    $sqlConnection = $null

    try
    {
        $Error.Clear()

        $ServerInstance = SQL-Get-Server-Instance $DatabaseServer $InstanceName
        $sqlConnection = New-Object System.Data.SqlClient.SqlConnection
        $sqlConnection.ConnectionString = "Server=$ServerInstance;Database=master;Trusted_Connection=True;"

        $Command = New-Object System.Data.SqlClient.SqlCommand
        $Command.CommandType = 1
        $Command.Connection = $sqlConnection
        $Command.CommandText = "create login [$loginName] from windows with default_database=[master], default_language=[us_english]"
        $sqlConnection.Open()
        $Command.ExecuteNonQuery() | Out-Null
        $Command.CommandText = "exec master..sp_addsrvrolemember @loginame = N'$loginName', @rolename = N'sysadmin'"
        $Command.ExecuteNonQuery() | Out-Null
    }

    catch
    {
        $str = (([string] $Error).Split(':'))[1]
        Write-Error ($str.Replace('"', ''))
    }

    finally
    {
        if ($sqlConnection)
            { $sqlConnection.Close() }
    }
}

你这样称呼它:

Create-SQL-Login $env:COMPUTERNAME\JohnDoe $env:COMPUTERNAME
于 2013-05-17T14:12:23.920 回答
0

找到了更简单的东西

Add-SqlLogin -ServerInstance <Server> -LoginName <User> -LoginType <LoginType> -DefaultDatabase tempdb -Enable -GrantConnectSql -LoginPSCredential $Credential
((New-Object ('Microsoft.SqlServer.Management.Smo.Server') "<Server>").Roles | where {$_.Name -eq 'sysadmin'}).AddMember("<User>")

于 2018-04-26T19:51:19.530 回答