Hi, I have written a custom Cmdlet that passes the System.Collections.SortedList object to WriteObject(...) method of the base class (viz., System.Management.Automation.Cmdlet class).
When run, this cmdlet write the Key-Value pair formatted as table on the Powershell Console, but, when piped and Export-Csv cmdlet is used as follows, it doesn't write the Key-Value pair in the csv file.
Following is information from the Test.csv file after running the above command:
#TYPE System.Collections.SortedListCapacity,Count,Keys,Values,IsReadOnly,IsFixedSize,IsSynchronized,SyncRoot64,51,System.Collections.SortedList+KeyList,System.Collections.SortedList+ValueList,False,False,False,System.Object
Whereas I want the following information to be exported to the file:
Name,Value
Key1,Value1
Key2,Value2
Key3,Value3
Also, is there a way, to export a muti-valued attribute (property) of an object as comma separated values in the above CSV file?
Please help if someone know the trick.
Regards - Imran
Use WriteObject() to output an object to the pipeline in your Cmdlet.
For more information consult MSDN documentation here.
Hi Richard,
The WriteObject() method has already been used and that is why it is showing key-value pair on the PowerShell Console. Please go through the post carefully, and if you know, how to get required information (i.e. Key-Value pair) from the collection objects contained within an object using Export-Csv, just let me know.
Please keep in mind that I am using PowerShell console to export the information in the CSV file.
Regards
You are right, my bad. Needed to get that first cup of coffee down!
I think the problem is that you outputting a .Net object and then trying to pass that to Export-Csv which will not work.
You could either rewrite your Cmdlet to convert the Collection object to a PSObject or do the conversion in script:
function ConvertTo-Object($hashtable) { $object = New-Object PSObject $hashtable.GetEnumerator() | ForEach-Object { Add-Member -inputObject $object ` -memberType NoteProperty -name $_.Name -value $_.Value } $object } $hash = @{Name='Richard'; Status='Online'} ConvertTo-Object $hash | Export-Csv test.csv -NoTypeInformation
Result:
"Name","Status"
"Richard","Online"
Thank you Richard,
Now you get to that, and I m glad to know that you told me the same right thing that I found by going through different blogs and forums. Just one more thing, What if we have a Collection<PSObject> within a PSObject? Will Export-Csv cmdlet will take care of that as well?
I don't normally speed time creating cmdlets in C#, so I will answer this theoretically using script as the example.
If you were to create a custom object in PowerShell, say $a in a for loop, and then append that object to another, say $collection, by doing $collection += $a on each iteration, then you could export this collection by writing:
$collection | export-csv test.csv