Merging Two PowerShell Collections into One Output


In SharePoint users and groups are both security principles, and both share some common properties. One property, ID, is interesting as it is unique and never duplicated between the lists of users and group. I.e. if there is a user with an ID of 5 then there is never a group with an ID of 5.

In PowerShell there are two separate properties for users and groups, but I wanted to merge the two into one sorted list. Turns out, as long as both Select statements return columns with the same names, then they can be "added" to get a merged result.


Example: Users and Groups

$users = $web.SiteUsers | Select Id, Name
$groups = $web.Groups | Select Id, Name
$users + $groups | Sort Id


If you wanted to do it all in one line, then use a few parentheses:

($web.SiteUsers | Select Id, Name)  +  ($web.Groups | Select Id, Name) | Sort Id

What if the column names don't match (but have similar data types)? You will need to create a PowerShell custom column. In the example below I wanted to use the user's DisplayName property instead of the Name property so I had to create a custom column named "Name" to match the "Name" property in the groups Select.

$users = $web.SiteUsers | Select Id, @{Label="Name"; Expression={$_.DisplayName|}}
$groups = $web.Groups | Select Id, Name
$users + $groups | Sort Id



No comments:

Note to spammers!

Spammers, don't waste your time... all posts are moderated. If your comment includes unrelated links, is advertising, or just pure spam, it will never be seen.