I'm trying to query a SQL database and return only the messages that are produced, table results aren't important. I've looked at several answers online and came up with the following code, but every time I output the $message
it is empty.
Can someone tell me what I'm doing wrong here or if there's some hidden problem?
$server = 'SampleServer'
$sqlQuery = "print 'sample message';"
$sqlConnection = new-object System.Data.SqlClient.SqlConnection("Server=$server; Trusted_Connection=True;")
$sqlConnection.FireInfoMessageEventOnUserErrors = $true
#Listener for messages
$handler = [System.Data.SqlClient.SqlInfoMessageEventHandler]{$message = "$($_)"}
$sqlConnection.add_InfoMessage($handler)
#tried using events, but it also didn't return anything. Assumed $Event was some system variable?
# Register-ObjectEvent -InputObject $sqlConnection -EventName InfoMessage -Action {$message = "$($Event.SourceEventArgs)"} -SupportEvent
#run Query
$sqlConnection.Open()
$sqlCommand = $sqlConnection.CreateCommand()
$sqlCommand.CommandText = $SQLQuery
$adapter = New-Object System.Data.SqlClient.SqlDataAdapter $sqlcommand
$dataset = New-Object System.Data.DataSet
$adapter.Fill($dataSet) | out-null
$sqlConnection.Close()
#output $message results
write-host $message
Also, I can't use Invoke-SqlCommand
.
EDIT So, after tinkering with the code some more, there's not really a problem with it, but there's a problem with how the query message is being returned from the $handler
block. If I put a write-host
in the $handler
block it works just fine, but I need the information later in my script. I've tried these solutions to no avail (also added return $message
to $handler
):
$message = $sqlConnection.add_InfoMessage($handler) #nothing returned
$sqlConnection.add_InfoMessage($message = $handler) #just plain wrong
Is there a correct location to put an assignment in this situation?