Display arrays from object

Welcome Forums General PowerShell Q&A Display arrays from object

This topic contains 4 replies, has 4 voices, and was last updated by

 
Participant
2 months ago.

  • Author
    Posts
  • #166921

    Participant
    Topics: 3
    Replies: 7
    Points: 56
    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: 423
    Points: 676
    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: 483
    Points: 1,151
    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: 3
    Replies: 7
    Points: 56
    Rank: Member

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

  • #167035

    Participant
    Topics: 2
    Replies: 999
    Points: 1,946
    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).

     

     

You must be logged in to reply to this topic.