title: Storing output of Stored Procedure in file after calling it from Powershell
body: <p>I am trying to call a SP (Ola's maintenance script!) on a remote server (that part of the code works), and the output of the SP is the results of DBCC CHECKDB (so it's in the Message tab).</p>
  
  <p>I tried to put together some code to capture this Message output into a file on the remote server, but the file is not being created, though the SP completes fine.</p>
  
  <pre><code>$OutputFile = "\\XXX\E$\SQLAdmin\DatabaseCheckDB\ScriptOutput\ScriptOutput.txt"
  
  $handler = [System.Data.SqlClient.SqlInfoMessageEventHandler] {param($sender, $event) Out-File -filepath $OutputFile -inputobject $event.Message };
  
   $SqlConnection.add_InfoMessage($handler); 
   $SqlConnection.FireInfoMessageEventOnUserErrors = $true;
   $SqlConnection = new-Object System.Data.SqlClient.SqlConnection("Server=XXX;DataBase=master;Integrated Security=SSPI")
   $SqlConnection.Open() | Out-Null
  
  $cmd = new-Object System.Data.SqlClient.SqlCommand("dbo.DatabaseIntegrityCheck", $SqlConnection)
  $cmd.CommandType = [System.Data.CommandType]'StoredProcedure'
  
  $cmd.Parameters.Add("@Databases","ALL_DATABASES") | Out-Null
  
  $cmd.ExecuteNonQuery() | Out-Null
  
  $SqlConnection.Close()
  </code></pre>
  
  <p>Can anyone see what i'm doing wrong here? THanks in advance!</p>