Home > OS >  PowerShell: get object properties in a readable table
PowerShell: get object properties in a readable table

Time:07-15

I am trying to display StrongAuthenticationMethods from the azure object (user) in a more readable way inside of the script which will reset the MFA method.

When I call variable $mfa

$UserPname = Read-Host "Please enter e-mail address"
$AzureUser=Get-MsolUser -UserPrincipalName "$UserPname"

$methode = $AzureUser.StrongAuthenticationMethods
$mfa = $methode | Select-Object MethodType, IsDefault
$mfa

it gives me a nice table:

----------           ---------
PhoneAppOTP              False
PhoneAppNotification      True

When I try to write-host this variable:

Write-Host $mfa

It gives me:

Write-Host $mfa
@{MethodType=PhoneAppOTP; IsDefault=False} @{MethodType=PhoneAppNotification; IsDefault=
True}

How can I display this MethodType and IsDefault properties in the best readable way using write-host?

Thanks for the information in advance!

CodePudding user response:

Write-Host ($mfa | Format-Table | Out-String)

CodePudding user response:

To print synchronous, richly formatted output to the host (display), use the Out-Host cmdlet rather than Write-Host: Out-Host uses PowerShell's rich formatting system, whereas Write-Host essentially performs .ToString() stringification, which often results in unhelpful output.

# Forces instant output to the display, 
# but note that such output *cannot be captured*.
# Use ... | Format-Table | Out-Host to force tabular formatting,
# but with a custom object with 4 or fewer properties that isn't necessary.
$mfa | Out-Host

Judging by your later comments, the reason you want this is the well-known problem of the situational lack of synchronization between pipeline output and to-host output (as well as output to other streams), which can cause displayed output to print out of order.

# !! Read-Host executes FIRST
[pscustomobject] @{ print='me' }
Read-Host 'Press ENTER to continue'
# Workaround: Out-Host forces instant printing to the display,
#             but note that such output then cannot be captured. 
[pscustomobject] @{ print='me' } | Out-Host
Read-Host 'Press ENTER to continue'

The problem is limited to a very specific - albeit common - scenario: implicitly table-formatted output for types that do not have formatting data defined for them.

  • Related