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  Matt McNabb 2 years, 7 months ago.

  • Author
    Posts
  • #23361

    GS
    Participant

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

    Why GM returns Int32 instead Array in statement above?

  • #23363

    Dave Wyatt
    Moderator

    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

    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

    Dave Wyatt
    Moderator

    Yep!

  • #23396

    Matt McNabb
    Participant

    Another way is to use the GetType method of objects:

    $result.GetType()

You must be logged in to reply to this topic.