PowerShell comes with a bunch of Export- and ConvertTo- cmdlets so you can serialize object data to CSV, JSON, XML, and other formats. That’s great but it is not hard at all to create your own export functions.
For example, Export-Csv in Windows PowerShell always quotes values. If you don’t like quoted CSVs, you are out of luck. PowerShell 7 has addressed this with additional parameters, but creating your own Export-Csv function is really not hard at all.
Here is a simple example:
$Delimiter = ','
$init = $false
# write the headers
if ($init -eq $false)
$_.PSObject.Properties.Name -join $Delimiter
$init = $true
# write the items
$_.PSObject.Properties.Value -join $Delimiter
$a = Get-Service | ConvertTo-MyCsv
That’s really all: ConvertTo-MyCsv converts objects to non-quoted CSV, and you can even select the delimiter if you want (defaulting to “,”).
To quickly check the integrity of the generated CSV, convert it back to objects:
PS> $a | ConvertFrom-CSV | Out-GridView
All is fine, the conversion worked. And it is not slower than using ConvertTo-Csv.
Obviously, the conversion would fail if any data values would contain the delimiter (which is why ConvertTo-Csv quotes them) but that’s not the point here. You can easily fine-tune the function. What’s much more important is the beauty of auto-documenting objects in PowerShell.
To convert the objects to CSV (or any other format), simply access their hidden PSObject property (which is available for any PowerShell object). It describes the object and delivers all property names, values, and data types.
ReTweet this Tip!
Powered by IDERA