1
votes

i am trying to connect to a sql server from powershell and getting this error

Exception calling "Open" with "0" argument(s): "The target principal name is incorrect. Cannot generate SSPI context." At C:\Users\Musawwir\Downloads\remotely access db.ps1:10 char:1 + $Connection.Open() + ~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: ( [], MethodInvocationException + FullyQualifiedErrorId : SqlException Exception calling "Fill" with "1" argument(s):

I can connect to SQL SERVER from other machines through SSMS but can not connect through powershell, also the script runs fine on local machine.

Here is the code i am using :

[string] $Server= "tcp:DESKTOP-J9UQ90E,1433"
[string] $Database = "Eshop"


[string] $SQLQuery= "[dbo].[usp_getCustomerAge]"


$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "server='$Server';database='$Database';Connection Timeout=300;Integrated Security=TRUE;UID=ali;PWD=1234"
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
$Command.CommandText = $SQLQuery
$Command.CommandTimeout=500

$adp = New-Object System.Data.SqlClient.SqlDataAdapter $Command
$data = New-Object System.Data.DataSet 
$adp.Fill($data) | Out-Null


$data2 = ''
$emp = ''

foreach($Row in $data.Tables.Rows){
 [string]$C_name = $Row[0]

  $C_name
  $data2= $data2+ "|"+$C_name
  $C_name = $C_name+"|"
$C_name | out-file "d:\\test4.txt" -Append


}
$Connection.Close()

#$data2 | out-file "d:\\test4.txt"
1
You have to set Integrated Security=false if you want the credentials UID=ali;PWD=1234 to be used - Denis Rubashkin
Now getting this: Exception calling "Fill" with "1" argument(s): "The EXECUTE permission was denied on the object 'usp_getCustomerAge', database 'Eshop', schema 'dbo'." At line:19 char:1 + $adp.Fill($data) | Out-Null + ~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: ( [], MethodInvocationException + FullyQualifiedErrorId : SqlException - Wassauf Khalid
Thanks mate .. solved the problem .. the user ali wasn't having access to stored procedure .. changed user from ali to sa and integrated security to false solved the problem .. - Wassauf Khalid
Please make your comment into an answer and self-accept it. - T-Heron
Please make your comment into an answer and self-accept it. - T-Heron

1 Answers

1
votes

The user ali wasn't having access to stored procedure .. changed user from ali to sa and integrated security to false solved the problem