Powershell – How to combine two Powershell outputs so that command #2 is run on each output

exchangeexchange-2010powershell

I want to combine the commands Get-user and get-casmailbox so that I can get the "Company" from the first output, and the "ActiveSyncStatus" in the latter into a single output.

I also understand that I could write an explicit loop do generate the desired results, but I think a more compact syntax is possible using the $_. command (or similar)

Can someone show me the command that demonstrates a Get-CasMailbox that feeds the second command using a $_. property, and finally does a select-object of some combination of attributes between the commands?

The reason I ask is because I often have to join commands in this manner, and for loops are explicit and difficult for the helpdesk to copy and paste. I'd much rather have a single command line they can paste in.

Best Answer

Every time you use Write-Host, Jeffrey Snover kills a puppy. Or is it Don Jones? Maybe they both kill the puppy together in some sort of ceremony. That'd be weird.

[PS] C:\>"User1", "User2" | % { [PSObject]@{Name=$_; Company=$(Get-User $_).Company; ActiveSyncEnabled=$(Get-CASMailbox $_).ActiveSyncEnabled} }

Name                           Value
----                           -----
Name                           User1
Company                        Contoso
ActiveSyncEnabled              True
Name                           User2
Company                        Woodgrove
ActiveSyncEnabled              True

Edit: Or this:

[PS] C:\>Foreach($_ In Get-Mailbox) { [PSObject]@{Name=$_; Company=$(Get-User $_).Company; ActiveSyncEnabled=$(Get-CASMailbox $_).ActiveSyncEnabled} }

The Exchange Cmdlets catch you off-guard with how they handle pipeline input.

If you want the output objects to look less crammed together, you can add a Format-Table at the end, right before the final } ... however, beware that Format-* is almost as bad as Write-Host, in that it has the ability to break the object-ness of the output, so only format output as the very last thing you intend to do. Don't format output, and then try to pipe it in to another cmdlet.