1

Here's my current code:

[string] $Server= "server"
[string] $Database = "database"
[string] $UserSqlQuery= $("SELECT * FROM [dbo].[User]")
[string] $UserID = "userid"
[string] $Pass = "pass"

$resultsDataTable = New-Object System.Data.DataTable
$resultsDataTable = ExecuteSqlQuery $Server $Database $UserSqlQuery $UserId $Pass

# executes a query and populates the $datatable with the data
function ExecuteSqlQuery ($Server, $Database, $SQLQuery, $UserID, $Pass) {
    $Datatable = New-Object System.Data.DataTable

    $Connection = New-Object System.Data.SQLClient.SQLConnection
    $Connection.ConnectionString = "server='$Server';database='$Database';trusted_connection=true;User ID = '$UserID';Password='$Pass';"
    $Connection.Open()
    $Command = New-Object System.Data.SQLClient.SQLCommand
    $Command.Connection = $Connection
    $Command.CommandText = $SQLQuery
    $Reader = $Command.ExecuteReader()
    $Datatable.Load($Reader)
    $Connection.Close()

    return $Datatable
}

#validate we got data
Write-Host ("The table contains: " + $resultsDataTable.Rows.Count + " rows")

So I realize I can replace UserID and Password with Integrated Security=true in order to use Windows authentication. The problem is I'm trying to use a Windows authentication other than my current one to get on SQL. Is there any way to do this? Thanks.

1 Answer 1

1

If the SQL connection string needs to specify Integrated Security then user impersonation will be needed. If you hold down the shift key and right click the powershell icon you can run the powershell process as another user by selecting "Run As" and entering the correct Windows credentials.

If the script must start running under one Windows user, but then impersonate a different Windows user for the SQL connection, then some additional scripting will be needed to setup that impersonation. Here's a link that may be useful in working that out - http://poshcode.org/1867

Sign up to request clarification or add additional context in comments.

2 Comments

The link does not exist anymore. I am facing this issue currently and don't know how to login to sql server using windows authentication with PowerShell.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.