0

This script runs without any problems for a SQL Server connection:

[string] $connectionString = "Server=$server;Database=$database;Integrated Security = False; User ID = $uid; Password = $pwd;"

$sqlConn = New-Object System.Data.SqlClient.SqlConnection
$sqlConn.ConnectionString = $connectionString

$sqlConn.Open()
Write-Host "The connection is $($sqlConn.State)"
$command = $sqlConn.CreateCommand()
$command.CommandText = $query
$result = $command.ExecuteReader()
$sqlConn.Close();
Write-Host "The connection is $($sqlConn.State)"

$table = new-object “System.Data.DataTable”
$table.Load($result)

But only with that result

The connection is Open
The connection is Closed

I have tried many proper SQL queries which run in Management Studio without any problems. Any hint how to properly execute and maybe check the SQL connection?

3
  • What result do you expect? Commented Feb 25, 2021 at 12:56
  • By the way, you should dispose your connection and reader, see stackoverflow.com/questions/42107851/… Commented Feb 25, 2021 at 13:13
  • thanks for your replies. Thought it's all covered in the accepted answer Commented Feb 25, 2021 at 14:52

1 Answer 1

2

The $result variable is a SqlDataReader. You need to leave the connection open when loading the data table from the reader:

$sqlConn.Open()
Write-Host "The connection is $($sqlConn.State)"

$command = $sqlConn.CreateCommand()
$command.CommandText = $query
$table = new-object “System.Data.DataTable”
$result = $command.ExecuteReader()
$table.Load($result)

$sqlConn.Close();
Write-Host "The connection is $($sqlConn.State)"

Consider simplifying using a SqlDataAdapter:

$dataAdapter = New-Object System.Data.SqlClient.SqlDataAdapter($query, $connectionString)
$table = new-object “System.Data.DataTable”
$dataAdapter.Fill($table)
Sign up to request clarification or add additional context in comments.

Comments

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.