Q: Run SQL Query With Execute-SQLQuery I am trying to use powershell to run a SQL Query.  I am hitting 2 errors, and not sure how to resolve.  This is my syntax
Function Execute-SQLquery 
{

  $QueryString = "Select employeename, employeeaddress, employeephone from employeefile where et = 'Active'"
  $Date = Get-Date -f 'MM.dd.yy'
  $FilePath = "R:\Test\Testing\"

  $SD = "M:\\CSV\Template\Try.csv"

  $server = "server"
  $database = "db"

  $connectionTemplate = "Data Source={0};Integrated Security=SSPI;Initial Catalog={1};"
  $connectionString = [string]::Format($connectionTemplate, $server, $database)
  $conn=New-Object System.Data.SqlClient.SqlConnection($connectionString)

  $cmd=$conn.CreateCommand()
  $cmd.CommandText = $QueryString   

  $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter($cmd)
  $dt = New-Object System.Data.DataTable
  $rowCount=$SqlAdapter.Fill($dt)

  [System.IO.Directory]::CreateDirectory($SD)
  $DataSet.Tables[0] | Export-Csv $SD -NoTypeInformation


  $connection.Close()
}

And here are the errors:

Can not index into a null aray  $DataSet.Tables[0] | Export-CSV $SD - NoTypeInformation
You can not call a method on a null-valued expression $connection.Close()


A: You just have two typos here. I will assume it is a result of your code biting ( grabbing snippets from more than one place and putting them together )from the internet to make your solution


*

*$dt is not the same as $dataset

*$conn  is not the same as $connection
In both cases update your script to be using the former. 
