Syntax To Export Query To CSV File

No error is thrown, but the data is not actually exported.  What did I miss or type incorrectly?  I am a complete beginner here, so sorry if this is something easys.

Function Execute-SQLquery {
	$Date = Get-Date -f 'MM.dd.yy'
	$MainPath = "C:\ReadyToPrint"
	$filename = "C:\TestBook\CSVTest.csv"
	$server = "RoyGBiv"
	$database = "Sparkler"
	$SelectQuery = "Select employeefirstname, employeelastname, employeeaddress, employeephone from employees"
	$connectionTemplate = "Data Source={0};Integrated Security=SSPI;Initial Catalog={1};"
	$connectionString = [string]::Format($connectionTemplate, $server, $database)
	$connection=New-Object System.Data.SqlClient.SqlConnection($connectionString)
	
	$cmd=$connection.CreateCommand()
	$cmd.CommandText = $SelectQuery	
	
	$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter($cmd)
	$dataset = New-Object System.Data.DataTable
	$rowCount=$SqlAdapter.Fill($dataset)
	
    if ($rowCount -gt 0)
    {
		if(!(Test-Path -path "$MainPath\$Date\"))
		{
			New-Item "$MainPath\$Date\" -type directory
		}	
		$dataset.Tables[0] | Export-Csv $filename -encoding "unicode"
    } 
	$connection.Close()
}

September 8th, 2015 1:24pm

First troubleshooting step - are you actually getting any data from your query?

If you have no idea what any of this is doing, then you really should start from the beginning:

http://technet.microsoft.com/en-us/scriptcenter/dd742419.aspx

Free Windows Admin Tool Kit Click here and download it now
September 8th, 2015 1:31pm

Yes, I have verified that my dataset is populating.
September 8th, 2015 1:55pm

Okay, then I'd put in some trace statements to verify that you're actually getting into your if statements.

This is one of those few times that Write-Host usage is very appropriate.

Free Windows Admin Tool Kit Click here and download it now
September 8th, 2015 2:04pm

Change this:

$SqlAdapter=New-Object System.Data.SqlClient.SqlDataAdapter($cmd)
$dt=New-Object System.Data.DataTable
if($SqlAdapter.Fill($dt)){
    $dt| Export-Csv $filename -encoding "unicode"
} 
$connection.Close()


You are addressing a dataset when you have created a single "datatable".

September 8th, 2015 2:59pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics