I have found a great answer on Stack Overflow that explains how to have a powershell function that runs some SQL to return a single value.
What I'm not understanding is how to call the function and place the result into a variable that I can use later? Any help would be appreciated
https://stackoverflow.com/a/22715645/2461666
[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($1)
}
$Connection.Close()
}
This is what I am currently trying but it doesn't seem to be working at all...
$myvariable = GenericSqlQuery