Invoke-Sqlcmd returning unwanted columns such as RowError, HasErrors

I’ve been performing some SQL queries recently using PowerShell and Invoke-SqlCmd.  Here is a simple example of returning a list of devices (a single column of data) from a database:

Of course I pipe this into Export-CSV like so:

When we read the exported data in the CSV we expect one column of data called ‘Device’.  However, instead we can also see columns called RowError, HasErrors and others!  And whilst I’m not sure why these appear, we can omit them like so:

and of course if we wanted to pipe this into a CSV we can do so like this:

And voila.  We only get the columns of data that we asked for!

Export Dynamic Data to a CSV using PowerShell

This post explains how to export dynamic data to a CSV using PowerShell.  I find that hashtables are quite useful for various scenarios when scripting in PowerShell.  We can also utilise them when exporting data using Export-CSV.

I provide two approaches to this.  Both approaches work by adding hashtables to an array.  By default if you export an array of hashtables to an array you will lose the column ordering.  With PowerShell 2 we can circumvent this issue by using ‘Select’ and specifying the order of the columns we would like to select:

With PowerShell 3 we can simplify this, by specifying the [ordered] type for our hashtable: