Powershell SQL SELECT output to variable

Alternatively you could use the following code, if you are looking for simple return values rather than tables for processing later.

[string] $Server= "10.0.100.1",
[string] $Database = "Database123",
[string] $SQLQuery= $("SELECT [FeedID] FROM [dbo].[FeedList] WHERE [FeedFileName] = 'filename.txt'")

function GenericSqlQuery ($Server, $Database, $SQLQuery) {
    $Connection = New-Object System.Data.SQLClient.SQLConnection
    $Connection.ConnectionString = "server='$Server';database='$Database';trusted_connection=true;"
    $Connection.Open()
    $Command = New-Object System.Data.SQLClient.SQLCommand
    $Command.Connection = $Connection
    $Command.CommandText = $SQLQuery
    $Reader = $Command.ExecuteReader()
    while ($Reader.Read()) {
         $Reader.GetValue(0)
    }
    $Connection.Close()
}

It looks like $FeedID (the variable you put the SQL output in) should have a FeedID property (from the single row returned).

Try this:

$FeedID.FeedID

Tags:

Sql

Powershell