title: Printing messages from SQL in Azure Automation powershell script doesn't work
body: <p>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.</p>
  
  <p>My code is taken from <a href="https://www.sqlskills.com/blogs/jonathan/capturing-infomessage-output-print-raiserror-from-sql-server-using-powershell/" rel="nofollow noreferrer">Capturing InfoMessage Output from SQL Server using PowerShell</a> and it works if I run it locally:</p>
  
  <pre class="lang-ps prettyprint-override"><code>Write-Output "Starting"
  
  $conn = New-Object System.Data.SqlClient.SqlConnection "Data Source=abc.database.windows.net,1433;Initial Catalog=def;Integrated Security=False;User ID=ghj;Password=qwe"
  
  ## Attach the InfoMessage Event Handler to the connection to write out the messages 
  $handler = [System.Data.SqlClient.SqlInfoMessageEventHandler] {param($sender, $event) Write-Output $event.Message }; 
  $conn.add_InfoMessage($handler); 
  $conn.FireInfoMessageEventOnUserErrors = $true;
  
  $conn.Open();
  
  $cmd = $conn.CreateCommand(); 
  $cmd.CommandText = "PRINT 'This is the message from the PRINT statement'"; 
  $cmd.ExecuteNonQuery(); 
  $cmd.CommandText = "RAISERROR('This is the message from the RAISERROR statement', 10, 1)";  
  $cmd.ExecuteNonQuery(); 
  $conn.Close();
  
  Write-Output "Done"
  </code></pre>
  
  <p>After I run the workbook, I see <code>Starting</code>, <code>-1</code> (from <code>ExecuteNotQuery</code> result) and <code>Done</code> but not messages from SQL.</p>
  
  <p><code>Register-ObjectEvent</code> from <a href="https://stackoverflow.com/a/7775500/1171619">this answer</a> doesn't work either:</p>
  
  <pre class="lang-text prettyprint-override"><code>Register-ObjectEvent : Cannot register for the specified event. 
  An event with the name 'InfoMessage' does not exist. Parameter name: eventName
  </code></pre>
  
  <p>What am I doing wrong?</p>