Question:
This is probably more of a ‘how does PowerShell handle variables and piping’ rather than a specific programmatical question, but since it seems like strange behaviour (to me) I thought I’d post it here.
I just had some difficulties exporting a variable to a CSV using PowerShell and found this Stack question that helped me a lot. However, when fiddling around with the output I got two different results depending on how I called the Export-CSV
function.
I have a custom PS object that looks roughly like this:
1 2 3 4 5 6 7 |
Account Partner ProjectName ProjectPhase 1 A Test Start 2 B Test2 Start 3 A Test4 End 4 C Test3 Middle .... |
When I use the following line it correctly outputs the CSV file:
1 2 |
$csvBody | Export-Csv -Path "$targetPath\$fileName" -Encoding Unicode -NoTypeInformation |
However, when I use the following line it doesn’t:
1 2 |
Export-Csv -InputObject $csvBody -Path "$targetPath\$fileName" -Encoding Unicode -NoTypeInformation |
In this case, the output looks like this:
Count,”Length”,”LongLength”,”Rank”,”SyncRoot”,”IsReadOnly”,”IsFixedSize”,”IsSynchronized”
263,”263″,”263″,”1″,”System.Object[]”,”False”,”True”,”False”
I understand from this other Stack post that the output becomes the property of the $csvBody, which is an array. My question is why does this happen when I’m not piping the object to Export-CSV, but it doesn’t happen when I am using the pipe?
Answer:
Here everything works as design and not badly written :
In the second way, the inputobject is a #TYPE System.Object[]
as you can see if you keep TypeInformation.
When you call Export-Csv using the pipe, each object of the collection is sent to the process part of the Cmdlet.
Take a collection of integers :
1 2 |
$a = 1..4 |
then try :
1 2 |
$a | Get-Member |
It gives : System.Int32
Then try :
1 2 |
Get-Member -InputObject $a |
It gives : System.Object[]
So in your case the object exported is the array wich can be useful too.