0

I am having trouble with a PowerShell script calling a TSQL query result. I want the result of my SQL query to be assigned to the $Output variable as a single value, not a dataset. From my PowerShell script below the $Output variable returns…

$Output

Column1
--------
100

When I need the result to return a single value like the following…

$Output
100

Below is the PowerShell script I am using:

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Data Source= myserver;Initial 
Catalog=mydatabase;Integrated Security=SSPI;"

$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "select 100"
$SqlCmd.Connection = $SqlConnection

$DataAdapter = new-object System.Data.SqlClient.SqlDataAdapter $SqlCmd
$Dataset = new-object System.Data.Dataset
write-output $DataAdapter.Fill($Dataset) | Out-Null
$Output = $DataSet.Tables
$Output 

Any help would be greatly appreciated!

1 Answer 1

3

Is this what you're looking for?

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Data Source= myserver;Initial 
Catalog=mydatabase;Integrated Security=SSPI;"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "select 100"
$SqlCmd.Connection = $SqlConnection
$SqlConnection.Open()
$Output = $SqlCmd.ExecuteScalar()
$Output

$SqlCmd.ExecuteScalar() returns a scalar value. Hope it helps.

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

4 Comments

Definitely the way to go with a single value coming back.
This exactly what I was looking for. It works but for some reason, It returns two values instead of one. Do you have any ideas on why is that?
Have you executed it as is? If not, please share your code.
Great! Glad I could help.

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.