Question

I have a binary cmdlet Get-CustomPSObject. When I do something like:

Get-CustomPSObject > a.txt

the result is stored as a plain text, meaning that the Get-CustomPSObject is working fine.

However when I try:

Get-CustomPSObject | Export-csv a.csv

The a.csv file becomes:

"Capacity","Count","IsReadOnly","IsFixedSize","SyncRoot","IsSynchronized"
"4","1","False","False","System.Object","False"

none of these fields are in my PSObject. I've no idea what they stands for. Any thoughts?

Was it helpful?

Solution

Export-CSV takes the first object it recieves to create the headers. Most likely, your Get-CustomPSOjbect runs a method/cmdlet/script that returns an object you didn't save. E.g. you use something like

get-childitem

and not

$files = get-childitem

inside your Get-CustomPSObject function.

EDIT Okay, so you're cmdlet is a binary cmdlet. Important information. I'm no expert in this, so please correct me if I'm wrong.

When you make a binary cmdlet that can output multiple objects, you need to write them one by one. One of the ideas behind PowerShell is the use of a pipeline that can use objects as they come without waiting for the complete array.

Because of your current "design flaw" in your binary cmdlet, Export-CSV tries to export the array(as one item) to a csv-file and not the elements inside.

You now use this:

WriteObject(list/array of objects)

This is bad. It outputs all objects at the same time.

To fix it, run this at the end of your "object-creation-loop":

WriteObject(mycurrentobject) 

This is good. You enable the use of pipeline and every object is sent out one by one when they're created. Export-CSV can then recieve each object and convert them to csv-format.

OTHER TIPS

In your first example using > the output is run through Powershell formatting system while in the second using export-csv it is not.

If you look at get-custompsobject | gm you should see those extra properties that aren't shown in console or sent to your text file.

For export-csv you can control which properties are sent to the csv file using select-object

get-custompsobjct | select-object column1, column2 | export-csv a.csv
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top