Devon J
Devon J

Reputation: 23

Exchange: Get-Mailbox output different in script vs command-line

In Powershell, I get different output from Get-Mailbox when running in a script vs command-line.

Script:

$credy = get-credential

$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $credy -Authentication Basic –AllowRedirection

Import-PSSession $session

Get-Mailbox

Output - Script:

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Script     1.0        ...                                 {Add-AvailabilityAddressSpace, Add-DistributionGroupMember...

RunspaceId                             : ...
Database                               : ...
MailboxProvisioningConstraint          :
MessageCopyForSentAsEnabled            : False
MessageCopyForSendOnBehalfEnabled      : False
MailboxProvisioningPreferences         : {}
UseDatabaseRetentionDefaults           : False
RetainDeletedItemsUntilBackup          : False

Output - Command-line:

PS C:\> Get-Mailbox

Name                      Alias                ServerName           ProhibitSendQuota
----                      -----                ----------           -----------------
mailbox1                  mb1                  ...                  ... 
mailbox2                  mb2                  ...                  ...
mailbox3                  mb3                  ...                  ...

When running Get-Mailbox in a script, I get the full mailbox details. However, when running through command-line, I get a list of the mailboxes. Why am I getting different outputs? I would like for the script to output just a list of the mailboxes.

Upvotes: 2

Views: 1244

Answers (1)

Frode F.
Frode F.

Reputation: 54971

Output (objects) from a script/function/cmdlet is sent down the pipeline when it's not saved. The pipeline is a stream of objects and PowerShell starts writing the output to the console/host as soon the first object arrives as long as you're not piping it to another function.

Because this is a stream, PowerShell needs to guess from the start how it should output the last object and it uses the format/view of the first object to decide, expecting every other object to be the same type. This is why the execution of a function, script etc. gets a broken view when it outputs different types of objects. The pipeline from your script contains both the result from Import-PSSession and mailbox-objects.

When you write in the console the pipeline is stopped after each command is done so once it's done the "view" is reset.

You could fix this by:

  • Replace the import-line with Import-PSSession $session | Out-Null so this won't set the "view".
  • Use something like Out-Host to write directly to the host instead of sending the mailboxes down the pipeline. Ex: Get-Mailbox | Out-Host.

Upvotes: 2

Related Questions