powershell piped input to export-csv different from -inputobject

Question:

In Powershell (3.0), I get different results when piping an object to Export-CSV than I do if I use the -IncludeObject parameter with the same object.

Example:

Why are the contents of one.csv and two.csv different?

(And in case it’s just me …)

one.csv =

two.csv =

For context, I’m trying to splat my parameters to Export-CSV, but I run into this when I pass -InputObject, and I can’t pipe the input and then splat the rest of the parameters.

Thanks.

Answer:

This is the expected behavior.

When you pipe in through the pipeline, arrays, collections, enumerable stuff, etc. gets processed item by item. This is usually what you want.

When you use -InputObject, it accepts the array as a single object.

The best way to see this is to use Get-Member:

In the first invocation, you’ll see the data type and members of each element. In the second invocation you’ll see the type and members of the collection object.

Depending on the cmdlet, you may not notice difference at all because it’s handling both cases (see the pipeline function at the end of my answer).

But in the case of Export-Csv, or ConvertTo-Json, or other serialization type cmdlets, you want this difference; otherwise it’s very difficult to serialize the array explicitly when you want to.

Another way to demonstrate it:

When writing your own pipeline functions, a common way to work around the different ways of receiving the object is to use the Process {} block along with foreach:

This works well because foreach doesn’t fail if you give it a single non-array object, it just executes once.

Source:

powershell piped input to export-csv different from -inputobject by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply