It is not clear what you expect as result from the 'addition'.
Indeed you cannot simply add two PSObjects together like you can with strings or arrays using +
.
1) If what you need is for the two objects to be combined in an array then this would do it:
$result = @()
$result += Get-Mailbox -Identity "XXXXX" | Select-Object DisplayName
$result += Get-Mailbox -Identity "XXXXX" | Select-Object PrimarySmtpAddress
2) If the result you seek is a new object with the properties of two objects combined, something like the function below can help:
function Join-Properties {
# combine the properties of two PSObjects and return the result as new object
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, Position = 0)]
$ObjectA,
[Parameter(Mandatory = $true, Position = 1)]
$ObjectB,
[switch] $Overwrite
)
if ($ObjectA -is [PSObject] -and $ObjectB -is [PSObject]) {
# combine the properties of two PSObjects
# get arrays of property names for both objects
[string[]] $p1 = $ObjectA | Get-Member -MemberType Properties | Select-Object -ExpandProperty Name
[string[]] $p2 = $ObjectB | Get-Member -MemberType Properties | Select-Object -ExpandProperty Name
# or do it this way
# [string[]] $p1 = $ObjectA.PSObject.Properties | Select-Object -ExpandProperty Name
# [string[]] $p2 = $ObjectB.PSObject.Properties | Select-Object -ExpandProperty Name
# if you do not want to overwrite common properties in in $ObjectA with the values from objectB
if (!$Overwrite) { $p2 = $p2 | Where-Object { $p1 -notcontains $_ } }
# create a new object with al properties of $ObjectA and add (or overwrite) the properties from $ObjectB to it.
$Output = $ObjectA | Select-Object $p1
foreach($prop in $p2) {
Add-Member -InputObject $Output -MemberType NoteProperty -Name $prop -Value $ObjectB."$prop" -Force
}
# return the result
$Output
}
else {
Write-Warning "Only [PSObject] objects supported. Both input objects need to be of same type."
}
}
Using your example on this:
$Var1 = Get-Mailbox -Identity "XXXXX" | select DisplayName
$Var2 = Get-Mailbox -Identity "XXXXX" | select PrimarySmtpAddress
$var3 = Join-Properties $Var1 $Var2
would yield a single PSObject with both properties DisplayName
and PrimarySmtpAddress
DisplayName PrimarySmtpAddress
----------- ------------------
Cassius Clay Mohammed.Ali@yourdomain.com
Hope that helps