title: How to export the output of a SQL query to Excel using PowerShell?
body: <p>I have a script which pulls data from a SQL database and gives the o/p in excel but the o/p comes under single column. I want to have it in different colums. This is my script:</p>
  
  <pre><code>     $SQLServer = ""
       $SQLDBName = ""
       $SqlQuery = ""
       $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
       $SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True; User ID = $uid; Password = $pwd;"
       $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
       $SqlCmd.CommandText = $SqlQuery
       $SqlCmd.Connection = $SqlConnection
       $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
       $SqlAdapter.SelectCommand = $SqlCmd
       $DataSet = New-Object System.Data.DataSet
       $SqlAdapter.Fill($DataSet)
       $DataSet.Tables[0] | out-file "C:\Users\sql.csv"
  </code></pre>
  
  <p>I also tried this script:</p>
  
  <pre><code>    $SQLServer = ""
      $SQLDBName = ""
      $SqlQuery = "select request_number,actioneer,audited_date from form_submission where actioneer ='XXXX' AND audited_date between '2020-05-19 00:00:00:000' and '2020-05-19 19:16:00:000';"| | Select @{n='request_number';e={request_number}}, @{n='actioneer';e={actioneer}} ,@{n ='audited_date';e={audited_date}}
      $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
      $SqlConnection.ConnectionString = "Server = $SQLServer; Database = 
      $SQLDBName; Integrated Security = True; User ID = $uid; Password = $pwd;"
      $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
      $SqlCmd.CommandText = $SqlQuery
      $SqlCmd.Connection = $SqlConnection
      $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
      $SqlAdapter.SelectCommand = $SqlCmd
      $DataSet = New-Object System.Data.DataSet
      $SqlAdapter.Fill($DataSet)
  
      $DataSet.Tables[0] | out-file "C:\Users\sql.csv" 
  </code></pre>
  
  <p>But this leads to the following error:</p>
  
  <pre><code>Exception calling "Fill" with "1" argument(s): "Must declare the scalar variable "@"."
  At C:\Users\sraghur\Documents\sql powershell.ps1:12 char:1
  + $SqlAdapter.Fill($DataSet)
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
      + FullyQualifiedErrorId : SqlException
  </code></pre>