Powershell – Select-object keeping same columns throughout script

powershellscripting

OK. I'm just drawing a blank here or I'm missing something obvious. In a Powershell (V3) script, I'm calling

Get-ADUser -Filter 'SAMAccoutnName -like $ADUserName' -Properties Name,SamAccountName,EmailAddress | Select-Object Name, SamAccountName, EmailAddress

It lists the data in the column format I would expect

Name           SamAccountName          EmailAddress
------         ---------------         ------------
User Name      username                user.name@co.com

That's not the problem. When I call a different command after that in the script (Exchange 2013 actually)

Get-Mailbox -Identity username | Select-Object Name, SAMAccountName, PrimarySMTPAddress

I only get the corresponding columns from the earlier Select-Object with no headers:

User Name     username

Even if I specifically ask for a different set such as that "PrimarySMTPAddress" from above.

What am I missing here? This is driving me crazy.

Thanks in advance.

Best Answer

The problem here is the fact that if you run select-object as a last cmdlet in pipeline with different set of properties, PowerShell will not "implicitly" call Out-Default for each command, so it won't "reset" formatting.

But what is not done implicitly, can always be done explicitly. Just output any command (maybe except last one) to Out-Default:

ls | select Name | Out-Default
ls | select DirectoryName