Union-Object

Most native PowerShell cmdlets  that handle an array of objects (like e.g. Export-CSV) only look to the first object to define the concerned  properties. This behavior can lead to unexpected results.  Consider the following object:

If you simply display this object array, only the Id property will be listed:

You might quickly fix this by aligning the properties of the first object with the rest of the objects (Name = $Null):

This will work for most of the cases:

But not in every case:

In other words, it is required to align every object in de array to prevent that you lose any properties. The quickest way is to use the Select-Object cmdlet: Select-Object Id, Name, knowing that just selecting all objects: Select-Object *, doesn’t resolve the issue. This mean that it is still required to iterate through all the objects to define all the properties.

Cmdlet

Syntax

<Object[]> | Union-Object [[-Property] <String[]>]

Parameters

[-Property] <String[]>

Redefines the properties, if omitted all objects will be scanned to define the common properties.

Example:

$list | Union-Object | Export-Csv

The Union-Object cmdlet was originally published at StackOverflow

Leave a Reply