title: Trying to write a data set from a SQL query out to a CSV file in Powershell
body: <p>I would like to create a CSV file (with no headers if possible) from a SQL query I make.  My powershell is below.  It reads the DB no problem and I see row results come back from printint to stdout.  But I can't seem to figure out how to get the results into a CSV file.</p>
  <p>The txt file created from my powershell only has one line it:</p>
  <h1>TYPE System.Int32</h1>
  <p>Which seems to me like it is just outputing the data type or something. It seems odd it is In32 but maybe that is because it is a pointer to the object?</p>
  <p>I saw one article that used Tables[0] when using a data set but when I replaced my last line with
  $QueryResults.Tables[0] | export-csv c:\tests.txt
  It gave me an error saying it couldn't bind an argument to parameter because it was null.</p>
  <pre><code>function Get-DatabaseData {
  param (
      [string]$connectionString,
      [string]$query,
      [switch]$isSQLServer
  )
  if ($isSQLServer) {
      Write-Verbose 'in SQL Server mode'
      $connection = New-Object -TypeName System.Data.SqlClient.SqlConnection
  } else {
      Write-Verbose 'in OleDB mode'
      $connection = New-Object -TypeName System.Data.OleDb.OleDbConnection
  }
  $connection.ConnectionString = $connectionString
  $command = $connection.CreateCommand()
  $command.CommandText = $query
  if ($isSQLServer) {
      $adapter = New-Object -TypeName System.Data.SqlClient.SqlDataAdapter $command
  } else {
      $adapter = New-Object -TypeName System.Data.OleDb.OleDbDataAdapter $command
  }
  $dataset = New-Object -TypeName System.Data.DataSet
  $adapter.Fill($dataset)
  $dataset.Tables[0]
  }
  
  $QueryResults = Get-DatabaseData -verbose -connectionString 'Server=localhost\SQLEXPRESS;;uid=sa; pwd=Mypwd;Database=DanTest;Integrated Security=False;' -isSQLServer -query &quot;SELECT * FROM Computers&quot;
  foreach($MyRow in $QueryResults) {
  write-output $MyRow.computer
  write-output $MyRow.osversion
  }
  
  $QueryResults | export-csv c:\tests.txt
  </code></pre>
  <p>I added a line to print $QueryResults to stdout and below is the output in the console of that and the write form my for loop to show what my $QueryResults has.</p>
  <pre><code>5
  
  
  computer         : localhost
  osversion        :
  biosserial       :
  osarchitecture   :
  procarchitecture :
  
  computer         : localhost
  osversion        :
  biosserial       :
  osarchitecture   :
  procarchitecture :
  
  computer         : not-online
  osversion        :
  biosserial       :
  osarchitecture   :
  procarchitecture :
  
  computer         :
  osversion        : win8
  biosserial       :
  osarchitecture   :
  procarchitecture :
  
  computer         : dano
  osversion        : win8
  biosserial       :
  osarchitecture   :
  procarchitecture :
  
  localhost
  
  localhost
  
  not-online
  
  
  win8
  dano
  win8 
  </code></pre>