1

So I have this connection

$connectionString = "Data Source=Something ;Initial Catalog=Something ;Integrated Security=SSPI" 
$connection = New-Object -TypeName System.Data.SqlClient.SqlConnection($connectionString)
$query = "select MAX(ID) from [dbo].[Table];" 
$command = New-Object -TypeName System.Data.SqlClient.SqlCommand($query, $connection)
$connection.Open()
$NewID = $command.ExecuteScalar() 
$connection.Close()

echo $NewID

And it works fine and does the job. Say I want to INSERT A ROW. Do I need the last 3 lines possibly with another method in $command.method()? In which line is the query actually executed?

Question 2: What method should I use if I want to get the whole result set to PowerShell?

2 Answers 2

1

If you want to execute a query without a result (like an INSERT) you can use ExecuteNonQuery

$command.ExecuteNonQuery()

If you want to to return non-scalar results, use ExecuteReader.

Sign up to request clarification or add additional context in comments.

2 Comments

So '$command = New-Object -TypeName System.Data.SqlClient.SqlCommand($query, $connection)' does not do anything?
It creates the SqlCommand object that you use for adding parameters, executing SQL commands and returning the results. Have a look at the docs.
1
###...your code up to $NewID = ...

$rdr = $command.ExecuteReader(1)
#get-type $rdr

$dt = new-object system.data.datatable
$dt.load($rdr)

$dt | out-gridview

1 Comment

Your answer is not bad but maybe you should explain it.

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.