2

I'm trying to connect my script to a Database. Previously I made it with:

psexec \\servername -accepteula sqlcmd.exe -U username -P password -S database -Q query

Now, I want to convert it into powershell code. I'm trying this:

Enter-PSSession servername
$SQLCred = New-Object System.Data.SqlClient.SqlCredential("username","password")
$Connection = New-Object System.Data.SqlClient.SqlConnection("Database",$SQLCred)
$Connection.Open()

But I always get this error:

Exception calling "Open" with "0" argument(s): "Login failed for user 'username'."

Of course I'm sure the credentials are correct. Which could be the difference between the two modes of connection?

2 Answers 2

1

Credentials are provided in the connection string:

$instance = "myInstance"
$userId = "myUserId"
$password = "myPassword"

$connectionString = "Data Source=$instance;Integrated Security=SSPI;Initial Catalog=master; User Id=$userId; Password=$password;"

$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()

If you have an existing credential object, you can use it like this:

$cred = New-Object System.Data.SqlClient.credential($userId, $password)
$connectionString = "Data Source=$Instance;Integrated Security=SSPI;Initial Catalog=master; User Id = $($cred.username); Password = $($cred.GetNetworkCredential().password);"
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
Sign up to request clarification or add additional context in comments.

Comments

0
    $SQLCredential = New-Object System.Data.SqlClient.SqlCredential($SQLUserName, $SQLPassword)
    $SQLServerConnection = New-Object System.Data.SqlClient.SqlConnection("Data Source=$SQLInstanceName; Initial Catalog=MASTER")
    $SQLServerConnection.Credential = $SQLCredential
    try
    {
        $SQLServerConnection.Open()
    }

1 Comment

I can see how this is different from the code in the question, but a short explanation why this code works, while the above one doesn't, would greatly benefit the uninitiated.

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.