A
A
alexeyborisov752020-12-03 17:28:59
PowerShell
alexeyborisov75, 2020-12-03 17:28:59

Why does PowerShell export nonsense when exporting SQL query result to CSV?

I don't understand what I'm doing wrong. I have a PowerShell script, it connects to the database, makes a request and returns the result, I need to save this result in excel and CSV

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=localhost\SQLEXPRESS;Database=msdb;Trusted_Connection=True;"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "Select * from MSdbms"
$SqlCmd.Connection = $SqlConnection
$DataAdapter = new-object System.Data.SqlClient.SqlDataAdapter $SqlCmd
$Dataset = new-object System.Data.Dataset
write-output $DataAdapter.Fill($Dataset) | Out-Null
$Output = $DataSet.Tables
$Output 

Export-Csv -InputObject $Output -Append -NoTypeInformation -Path C:\Users\users\TestScripts\Report.csv


The result is displayed correctly on the screen, 5fc8f61b1cb7b167587028.png

but some kind of hat is displayed in CSV, I don’t understand where the error is.5fc8f628c9213321771822.png

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
alexeyborisov75, 2020-12-03
@alexeyborisov75

Everything is much simpler, as it turned out

Invoke-Sqlcmd -Query "Select * from MSdbms" -ConnectionString "Server=localhost\SQLEXPRESS;Database=msdb;Trusted_Connection=True;" | Export-Csv  -Delimiter ';' -Path C:\Users\user\TestScripts\Report.csv -notypeinformation

R
Roman Bezrukov, 2020-12-03
@NortheR73

And if so?
$output | select dbms_id,dbms | export csv...

M
MaxKozlov, 2020-12-03
@MaxKozlov

because you put Tables in $Output, and you need the first one
$DataSet.Tables[0] | Export-Csv ....

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question