How to format output when exporting SQL query to CSV

北城以北 提交于 2019-12-04 18:57:05

You might run in to trouble removing the quotes, but if that's what you really want then the following should achieve it.

-NoTypeInformation will remove the additional type information you are seeing.

($DataSet.Tables[0] | ConvertTo-Csv -Delimiter ";" -NoTypeInformation) -replace "`"", "" | `
Out-File -Force $extractFile

This uses convertto-csv to convert to a string representation of the csv followed by replacing all instances of " with nothing and the final string is piped to Out-File.

...and, to get rid of the header record, if you first convert the data to csv (Convert-Csv), then pipe those results to Select to skip the 1st record:

($DataSet.Tables[0] | ConvertTo-Csv -Delimiter "`t" -NoTypeInformation ) -Replace "`"","" | Select -skip 1 | Out-File blahblahblah...

Agreed export-csv isn't the best tool for the job. I would use sqlcmd.exe or bcp.exe provided SQL Server command-lines tools are installed. You could also build a simple routine to create a CSV from a datatable:

$result = new-Object text.stringbuilder
$dt = $DataSet.Tables[0]

foreach ($dr in $dt.Rows) {
           for ($i = 0; $i -lt $dt.Columns.Count; $i++) {

                $null = $result.Append($($dr[$i]).ToString())
                $null = $result.Append($(if ($i -eq $dt.Columns.Count - 1) {"`n" } else { ","} ))
            }
}

$result.ToString()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!