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.
The txt file created from my powershell only has one line it:
TYPE System.Int32
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?
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.
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 "SELECT * FROM Computers"
foreach($MyRow in $QueryResults) {
write-output $MyRow.computer
write-output $MyRow.osversion
}
$QueryResults | export-csv c:\tests.txt
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.
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