Why "GM" on Array returns Type of element of array instead of Array?

Welcome Forums General PowerShell Q&A Why "GM" on Array returns Type of element of array instead of Array?

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

 
Participant
3 years, 9 months ago.

  • Author
    Posts
  • #23361
    GS

    Participant
    Points: 12
    Rank: Member

    $result = @(1,2,3)
    $result | gm

    Why GM returns Int32 instead Array in statement above?

  • #23363

    Member
    Points: 0
    Rank: Member

    When you send an array to the pipeline, PowerShell pipes in the elements of that array to the next command, one at a time. So Get-Member, in this case, is seeing three separate Int32 objects instead of a single array object.

    There are two ways around this. You can wrap the array in yet another array using the unary comma operator, like so:

    ,$result | Get-Member
    

    Or, you can call Get-Member without using the pipeline input:

    Get-Member -InputObject $result
    
  • #23364
    GS

    Participant
    Points: 12
    Rank: Member

    So in essense anytime I need to check any object for type I can not use results of | gm as reliable information since in cases where objects implements Ienumerable I would not get correct result and I always has to use Get-Member -InputObject instead

  • #23365

    Member
    Points: 0
    Rank: Member

    Yep!

  • #23396

    Participant
    Points: 2
    Rank: Member

    Another way is to use the GetType method of objects:

    $result.GetType()

The topic ‘Why "GM" on Array returns Type of element of array instead of Array?’ is closed to new replies.