Properties across Pipeline

Hello everyone, I’m fairly new to PS and also not a native english speaker so searching sometimes gets hard.

I’m need to get from Exchange all PrimarySMTPAddress with their last logon from a particular domain but I lose properties across the pipeline. Check it out:

Get-Mailbox -ResultSize Unlimited | where {$.PrimarySmtpAddress -like “*@domain.com”} | get-mailboxstatistics | where {$.lastlogontime -lt (get-date).adddays(-90)} | select primarysmtpaddress,lastlogontime

The issue is that primarysmtpaddress comes empty, so I’m guessing I’m losing the property value across the pipe:

primarysmtpaddress LastLogonTime


                                                                       4/10/2014 9:10:59 AM

Any help will be appreciated.

Thanks,
Valentin

Yep, you’ve got the right idea. The by time you get to your Select call, you’re looking at a mailboxStatistics object, which has no PrimarySmtpAddress property. How you deal with this depends on whether you’re running PowerShell 4.0 or not. In PowerShell 4.0, they added a new common parameter called -PipelineVariable which can help this situation with a “one-liner” approach like this:

Get-Mailbox -ResultSize Unlimited | where {$_.PrimarySmtpAddress -like "*@domain.com"} -PipelineVariable mailbox | get-mailboxstatistics | where {$_.lastlogontime -lt (get-date).adddays(-90)} | select @{Name = PrimarySmtpAddress; Expression = { $mailbox.PrimarySmtpAddress }}, LastLogonTime

If you’re running an older version of PowerShell, then you don’t have -PipelineVariable, and have to resort to a loop with a nested pipeline instead. The performance isn’t quite as good, and the code doesn’t look nice on one line anymore, but the idea is the same:

Get-Mailbox -ResultSize Unlimited |
where {$_.PrimarySmtpAddress -like "*@domain.com"} |
ForEach-Object {
    $mailbox = $_
    $mailbox | get-mailboxstatistics | where {$_.lastlogontime -lt (get-date).adddays(-90)} | select @{Name = PrimarySmtpAddress; Expression = { $mailbox.PrimarySmtpAddress }}, LastLogonTime
}

Awesome, thanks a lot Dave.

Regards,
Valentin