Powershell – How to combine properties in Powershell from multiple Objects

exchangeexchange-2010powershellscripting

Many times I've needed to combine data that can only be retrieved from two separate powershell CMDLETs into a single dataset for export. I believe this should be do-able by creating a PSObject and collecting data there, then selecting data from the PSOBject and exporting it.

An example of what I'm trying to do. This does not work yet.

$OU1 = 'Contoso.com/Contoso Service Accounts'
$MBXStats = get-mailbox -OrganizationalUnit $OU1 | Get-MailboxStatistics
$MBXDN = get-mailbox -OrganizationalUnit $OU1 | Select DistinguishedName

$bucket = @()

foreach ($MBX in $MBXStats){

$PropertyObj = New-Object psobject -Property @{
    DisplayName = $MBXStats.DisplayName
    ItemCount = $MBXStats.ItemCount
    TotalItemSize = $MBXStats.TotalItemSize
    LastLogonTime = $MBXStats.LastLogonTime
    OriginatingServer = $MBXStats.OriginatingServer
    DistinguishedName = $MBXProps.DistinguishedName
    }
    $bucket += $PropertyObj
}

$bucket | Out-GridView

I have no idea how to even begin integrating the datagathering for $MBXDN = get-mailbox -OrganizationalUnit $OU1 | Select DistinguishedName into the script.

Best Answer

It looks like you're trying to combine properties from multiple objects onto the output stream. I think the best way to accomplish your goal is to leverage calculated properties on your pipeline. However, in your code example MBXProps is an undeclared variable which may be the leading cause to why your process isn't working. Though you've likely cherry picked what code to show us (generally a bad idea) so I'll assume you're trying to integrate the MBX DN with your dataset.

$MBXStats = get-mailbox -OrganizationalUnit $OU1 | Get-MailboxStatistics
$MBXDN = get-mailbox -OrganizationalUnit $OU1 | Select DistinguishedName

$MBXStats | Select *,@{N="DistinguishedName";E="$($MBXDN.DistinguishedName)"}

Summarily, what you want to do is add a calculated property to the output. I'm being slightly lazy by valuing all * properties and not your chosen few, but you can adapt it to your needs. Of note you should try to always output objects to leverage the true power of Powershell.