Printing messages from SQL in Azure Automation powershell script doesn’t work

Question:

I’ve created a sample Azure Automation Powershell Runbook. I’m trying to execute a SQL command and then print the messages from that command into Workbook output.

My code is taken from Capturing InfoMessage Output from SQL Server using PowerShell and it works if I run it locally:

After I run the workbook, I see Starting, -1 (from ExecuteNotQuery result) and Done but not messages from SQL.

Register-ObjectEvent from this answer doesn’t work either:

What am I doing wrong?

Answer:

It seems in Azure Automation there is a scope problem calling Write-Output or Write-Host inside of the handler. Setting the message to a global variable in the handler and then calling Write-Output after ExecuteNonQuery worked for my purposes.

If you are expecting more than one message you could concatenate them to the variable instead.

However, in either case, they will not be raised when they are thrown, but after the query has finished.

EDIT: I found a solution that I like even better and wanted to share it. Use an object list in the handler…


…and after ExecuteNonQuery loop to write all the messages

Source:

Printing messages from SQL in Azure Automation powershell script doesn’t work by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply