Welcome Forums General PowerShell Q&A Display arrays from object

Viewing 4 reply threads
  • Author
    Posts
    • #166921
      Participant
      Topics: 5
      Replies: 9
      Points: 87
      Rank: Member

      Hello,

      I created object that have 2 simple arrays.

      $obiekt = New-Object psobject -Property @{
      ‘Name’ = @(‘Name1 Surname1’, ‘Name2 Surname2’);
      ‘UserPrincipalName’ = @(‘name1.surname1@XXX’, ‘name2.surname2@YYY’);
      };

      When I display this object by call its name $obiekt I got:

      UserPrincipalName Name
      —————– —-
      {name1.surname1@XXX, name2.surname2@YYY} {Name1 Surname1, Name2 Surname2}

      How to display values in columns?

      I tried:

      $obiekt | Format-Table

      and many other solutions, but without success.

    • #166936
      Participant
      Topics: 9
      Replies: 431
      Points: 737
      Helping Hand
      Rank: Major Contributor
      
      $obiekt = @() # Explicitly declares empty array
      
      $obiekt += New-Object psobject -Property @{
          Name              = 'Surname1'
          UserPrincipalName = 'name1.surname1@XXX'
      }
      
      $obiekt += New-Object psobject -Property @{
          Name              = 'Surname2'
          UserPrincipalName = 'name2.surname1@XXX'
      }
      
      $obiekt
      
    • #166948
      Participant
      Topics: 2
      Replies: 512
      Points: 1,309
      Helping Hand
      Rank: Community Hero

      Yeah, you can’t have a single property with multiple values and have it display in columns. PS’s display framework is designed around arrays of objects, rather than arrays of individual items. Gotta split that object in two to get the column display you’re after. ūüôā

    • #167020
      Participant
      Topics: 5
      Replies: 9
      Points: 87
      Rank: Member

      Okay. Now I understand. Thank you ūüôā

    • #167035
      Participant
      Topics: 2
      Replies: 1008
      Points: 2,055
      Helping Hand
      Rank: Community Hero

      You cannot do this with splitting the strings. Roughly, for example…

       

      $obiekt = @()
      
      'Name1 Surname1', 'Name2 Surname2' | 
      ForEach {
          $obiekt += New-Object psobject -Property @{
              Name              = ($PSItem -split ' ')[1]
              UserPrincipalName = $(($PSItem -split ' ')[0] + '.' + ($PSItem -split ' ')[1]) + '@XXX'
          }
      }
      
      $obiekt
      
      # Results
      <#
      UserPrincipalName  Name    
      -----------------  ----    
      Name1.Surname1@XXX Surname1
      Name2.Surname2@XXX Surname2
      #>

      Now, understand string concats can be a bit cumbersome. Yet, there are many ways to do it. The above is just Q&D (quick and dirty).

       

       

Viewing 4 reply threads
  • The topic ‘Display arrays from object’ is closed to new replies.