连接到 SQL 数据库时模拟另一个用户

Impersonate another user when connecting to SQL database

在TeamCity/in general 上连接到SQL 数据库时,模拟其他用户的最佳方式是什么?例如,如果 env.USERNAME/[Environment]::UserName 与您使用的不同。

我尝试了以下方法,但每次尝试都无法连接到数据库($varSQLServer 为空)。难道我做错了什么?几天来我一直在处理相同的代码行。请注意,由于资源限制,我使用的是 Powershell 2。

function connectToDb() {
    Param(
        [Parameter(Mandatory=$true)] [String]$varDBUser
        [Parameter(Mandatory=$true)] [String]$varDBPassword
        [Parameter(Mandatory=$true)] [String]$varDBServer
        [Parameter(Mandatory=$true)] [String]$varDBInstance
    )     

    [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null 
    $varSQLServer = New-Object -typeName Microsoft.SqlServer.Management.Smo.Server -argumentList "$varDBServer$varDBInstance"
    $varSQLServer.ConnectionContext.LoginSecure = $true 
    $varSQLServer.ConnectionContext.ConnectAsUser = $false 
    $varSQLServer.ConnectionContext.ConnectAsUserName  = $varDBUser 
    $varSQLServer.ConnectionContext.ConnectAsUserPassword = $varDBPassword

    try {
        varSQLServer.ConnectionContext.Connect()
    }
    catch {
        throw "Can't connect to SQL Server".
        Write-Error $_
        [System.Environment]::Exit(1)
    }
}

C#.NET 中的以下代码希望它能帮助您理解这个概念。

    var srvConnectionConn = new ServerConnection("WIN-DVGQDI73QR6");

srvConnectionConn.ConnectAsUser = true;
srvConnectionConn.ConnectAsUserName = @"administrator@mva";
srvConnectionConn.ConnectAsUserPassword = "*****";

srvConnectionConn.ConnectTimeout = 60;
srvConnectionConn.NonPooledConnection = true;

Server srv = new Server(srvConnectionConn);

我正在尝试使用域管理员帐户进行连接 mva\Administrator