Search code examples
powershellobjectazure-powershell

Powershell print sub-level objects in FT


I have the following generic structure:

  • Powershell command returns an object containing named fields and values. Some of those values are objects with another struct of names and values below them.
  • I want to simply print the results in a FL, but I want the sub-object values included.

The following code provides me the output I'm looking for, but I feel like I'm not doing this in a powershell-efficient way and I should be able to pipe this into a one-liner

foreach ($user in (Get-MsolUser | ?{$_.StrongAuthenticationmethods -ne $null})){
Write-host "$($user.UserPrincipalName) :: $($user.DisplayName)"
foreach($method in $user.StrongAuthenticationMethods){
write-host "`t$($method.MethodType)"
}}

I was hoping the above could be shortened to resemble the below non-functional code... is something like this possible to dump the property values when there could be a number of results between 0-X (max 4 in my case)?

Get-msolUser|?{$_.StrongAuthenticationmethods -ne $null} | select UserPrincipalName,Displayname,isLicensed,(StrongAuthenticationmethods | fl)

Solution

  • Use a calculated property:

    Get-MsolUser |
      Where-Object { $null -ne $_.StrongAuthenticationmethods } | 
      Select-Object UserPrincipalName, Displayname, isLicensed, @{
        Name='StrongAuthenticationmethods'
        Expression={ $_.StrongAuthenticationmethods.MethodType -join "`n" }
      } |
      Format-List
    

    The above uses Format-List (fl), but if you prefer a tabular representation via Format-Table (ft) instead, replace | Format-List with | Format-Table -Wrap.