Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot connect to SQL Server from PowerShell with domain credentials

I have a problem where I cannot connect to a SQL Server using domain credentials. Using the SA credentials it works and the query runs as expected. But when I use domain credentials, I get an error.

Here is the script:

$SQLServer = 'server.domain.com'
$SQLDBName = 'DBname'
$username  = "DOMAIN\user"
$password  = "password"

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection

#--> With SA, it works, with DOMAIN creds, it does not

#$SqlConnection.ConnectionString = "Server=$SQLServer; Database=$SQLDBName; User ID=sa; Password=SApassword;"
$SqlConnection.ConnectionString = "Server=$SQLServer; Database=$SQLDBName; User ID=$username; Password=$password;"

$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = 'select count (*) from my.table'
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$DataSet.Tables[0]

And here is the error I get when I run the script:

Exception calling "Fill" with "1" argument(s): "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

At C:\scripts\PowerShell\myscript.ps1:28 char:1
+ $SqlAdapter.Fill($DataSet)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SqlException

I should point out the fact that I am connecting to a SQL Server from a computer which is NOT in the domain (therefore I cannot use any sort of authentication passthrough).

Any ideas as to why I cannot connect with my domain credentials? I've followed other posts which offer advice on checking connections, firewalls etc. That's all in working order and the script runs perfectly as the sa (local) user. Just not on the domain..

like image 804
Mike J Avatar asked Jan 14 '23 20:01

Mike J


1 Answers

If you have SQL Credentials use something like this:

$ConnectionString = server=*serverName*;database=*databaseName*;user id=*userName*;password=*passWord*;

If you have Domain Credentials use something like this:

$ConnectionString = "server=*serverName*;database=*databaseName*;user id=*domain\username*;password=*passWord*;trusted_connection=true;"

This works in my environment. Of course after that you do:

$Connection = New-Object System.Data.SQLClient.SQLConnection($ConnectionString)
like image 117
Thomas Avatar answered Apr 08 '23 08:04

Thomas