I've found plenty of information on how to connect to SQL Server with PowerShell using either the currently logged in user with Windows authentication, or using a SQL Server account to connect with other credentials. I'm wondering if there's a way to connect with Windows authentication but impersonating another Windows user.
Here are the ways I have found it possible to use to connect to a SQL Server database using either Windows authentication or SQL Server authentication:
Windows authentication using .Net:
$Connection = New-Object System.Data.SqlClient.SQLConnection
$Connection.ConnectionString = "Data Source=$SQLServer;Integrated Security=$true;Initial Catalog=$Database"
$Connection.Open()
SQL Server authentication using .Net:
$CredentialObject = New-Object System.Management.Automation.PSCredential -ArgumentList $SQLUsername,$SQLPassword
$CredentialObject.Password.MakeReadOnly()
$SQLCredential = New-Object System.Data.SqlClient.SqlCredential($CredentialObject.UserName,$CredentialObject.Password)
$Connection = New-Object System.Data.SqlClient.SQLConnection
$Connection.ConnectionString = "Data Source=$SQLServer;Initial Catalog=$Database"
$Connection.Credential = $SQLCredential
Windows authentication using SqlServer
module:
Invoke-Sqlcmd -ServerInstance $SQLServer -Database $Database -Query "SELECT....."
SQL Server authentication using SqlServer
module:
Invoke-Sqlcmd -ServerInstance $SQLServer -Database $Database -Query "SELECT....." -Username $SQLUsername -Password $SQLPassword
I've noticed that the -Credential
flag exists for Invoke-Sqlcmd
but according to this post that too assumes SQL Server authentication and cannot use Windows authentication.
Are there any other options available if I want to impersonate a user using Windows authentication?
Thanks in advance