Hi All,
Below is the powershell script to connect a SQL DB using windows authentication by impersonating a user. The user should have login access to the server. Script can be highly useful when service id is used to access DB using powershell.
[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null
$ds=$null
$conn = New-Object -typeName Microsoft.SqlServer.Management.Smo.Server -argumentList "Servername"
$db = New-Object Microsoft.SqlServer.Management.Smo.Database
$conn.ConnectionContext.ConnectAsUser = $true
$conn.ConnectionContext.LoginSecure=$true
$conn.ConnectionContext.ConnectAsUserName = "username"
$conn.ConnectionContext.ConnectAsUserPassword ="password
$conn.Loginmode
$db = $conn.Databases.Item("dbname")
$ds = $db.ExecuteWithResults("select top 10 Name from Tablename")
Foreach ($t in $ds.Tables)
{
Foreach ($r in $t.Rows)
{
Foreach ($c in $t.Columns)
{
Write-Host $c.ColumnName "=" $r.Item($c)
}
}
}