Connect to SQL server using different AD user using powershell

Ashwan 536 Reputation points
2023-03-08T13:23:13.1966667+00:00

WE are having an issue with connecting to SQL server using active directory domain user (AD User ) to SQL server instance 2016. Its automatically pickup login local user NOT the new AD user(prod\Aduser1). not sure parameter are correct

$pass = 'Gvtddt6'
$sqlConn = New-Object System.Data.SqlClient.SqlConnection
$sqlConn.ConnectionString = “Server=SQLSERVER;TRUSTED_CONNECTION=TRUE;Encrypt=true;TrustServerCertificate = true;Initial Catalog=master;UID=domain\ADuser1;PWD=$pass;Integrated Security=true;”
$sqlConn.Open()
$sqlcmd = $sqlConn.CreateCommand()
$query = “ SELECT TOP (2)[equi_nce]
              FROM [test].[table1]”
$sqlcmd.CommandText = $query
$adp = New-Object System.Data.SqlClient.SqlDataAdapter $sqlcmd
$data = New-Object System.Data.DataSet
$adp.Fill($data) | Out-Null
$data.Tables

any one can help would be great

thanks

SQL Server Other
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2023-03-08T22:32:47.32+00:00

    First of all, you are saying TRUSTED_CONNECTION=TRUE. That means Windows authentication. Which means the current user.

    Next, even if you take out TRUSTED_CONNECTION, this part UID=domain\ADuser1;PWD=$pass is not going to work out as intended. When you specify UID+PASS, this always means SQL authentication. That is, the user must be an SQL login. In cannot be Windows user.

    When you log on to SQL Server with Windows authentication, you always do that with your current Windows user. If you want to connect as a different Windows user, you first need to perform a login into Windows, for instance with the RUNAS command. (It is also possible that PowerShell provides means for this, but that beyond the scope of the tag SQL Server.

    1 person found this answer helpful.

  2. Seeya Xi-MSFT 16,586 Reputation points
    2023-03-09T03:14:53.5566667+00:00

    Hi @Ashwan,

    You need to add this Authentication=ActiveDirectoryPassword;

    You need to choose your authentication method. It corresponds to the one here.

    User's image

    Best regards,

    Seeya


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".


  3. Pothiraj, Saranya-ADM 0 Reputation points
    2023-12-19T14:56:39.1533333+00:00

    @Ashwan, Did you get solution?

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.