r/PowerShell • • Aug 28 '24

Powershell and Types

Once upon a time I was a C/C++ programmer. I am trying to get my feet wet with PS to accomplish some maintenance tasks on my computer that might not justify either a command line or Windows app. The lack of typing in PS is really messing with my head. It seems as though variables can be created as any type and that "functions" in PS can return a wide variety of types.

How am I supposed to know what is in a variable if I cannot trace it back to its declaration and see a type?

Example question...

$filenames = Get-ChildItem -Path "D:\Brian's Stuff\Media\Data\Video\Santa Barbara\0001 - 0100\Santa Barbara 8493" -Filter *.mp4

So apparently this invocation of Get-ChildItem returns a collection. How do I know the collection type (is it an array? A linked list? An abstraction of a binary tree?) And what about the type of object being stored in the collection. How do I determine that without any variable typing? $filenames is a collection, but of what? And it all can change depending on what type of information I am asking Get-ChildItem for?

Maybe I need to find a strongly typed language. I don't get it. BTW I am literally 6 hours old with PS. Just started. Trying to learn only what I need to learn to get the job done. Don't intend to study the language out of intellectual curiousity.

11 Upvotes

32 comments sorted by

View all comments

Show parent comment

2

u/jortony Aug 29 '24

I'm not near a machine, but I would encourage you to pipe $YourCollectionObjectVariable into Get-Member then you will find it's type/s in the header (over the properties and methods) as previously described.

3

u/sysiphean Aug 29 '24

Hashtables and Ordered collections will return members for the collection. Every other common collection type, and every uncommon one I’ve seen, will return members for the objects inside the collection. And that specifically applies to default Array objects, which are the ones PowerShell creates by default.

That absolutely bit my ass when I was first learning PowerShell. (Which was just as 2.0 came out, so like 16 years ago?) It took me a bit to figure out what was going on, and to use Get-Member -InputObject instead of the pipe. Thats a lesson that sticks with you.

Try it when you’re back at a terminal; you’ll see.

1

u/sysiphean Aug 29 '24

Just to update here, because I am sitting at a console during a boring meeting:

I tested this against a bunch of collection types; what it boils down to is that any collection where the type's ImplementedInterfaces includes [System.Collections.IDictionary] will return the collection members when piped to Get-Member, but any collection where the type's ImplementedInterfaces includes [System.Collections.IList] will return the collection items' members when piped to Get-Member. (I did not check all 74 iDictionary implementing types, all 108 iList ones, or any of the 109 that implement neither but do implement iCollection, but tested more of the first two than I want to admit.)

You can test this yourself, or just look at my results below for 3 types each of IDictionary and IList. First off, I built the typed objects, filled with one Int32 and one String, with or without a key as needed:

PS /> $Hashtable          = @{ one=1; two="2" }
PS /> $iDictionary        = [System.Collections.IDictionary]@{ one=1; two="2" }
PS /> $OrderedDictionary  = [ordered]@{ one=1; two="2" }
PS /> $Array              = [array]@( 1, "2" )
PS /> $ArrayList          = [System.Collections.ArrayList]@( 1, "2" )
PS /> $List               = [System.Collections.Generic.List[System.Object]]@( 1, "2" )

Side note here: [array]@( 1, "2" ) and [array]@( 1, "2" ) and [array]@( 1, "2" ) all produce the exact same typed object, which you'll see below.

Then, we get the iDictionary based objects, which do work as you said, returning the members of the collection itself when piped to Get-Member.

In all these examples, I removed all but the first and last members for clarity.

PS /> $Hashtable | Get-Member

   TypeName: System.Collections.Hashtable

Name              MemberType            Definition
----              ----------            ----------
Add               Method                void Add(System.Object key, System.Object value), void IDictionary.Add(System.Object key, System.Object value)
    .  .  .
Values            Property              System.Collections.ICollection Values {get;}

PS /> Get-Member -InputObject $Hashtable

   TypeName: System.Collections.Hashtable

Name              MemberType            Definition
----              ----------            ----------
Add               Method                void Add(System.Object key, System.Object value), void IDictionary.Add(System.Object key, System.Object value)
    .  .  .
Values            Property              System.Collections.ICollection Values {get;}

PS /> $Hashtable.GetType()

IsPublic IsSerial Name                  BaseType
-------- -------- ----                  --------
True     True     Hashtable             System.Object


PS /> $iDictionary | Get-Member

   TypeName: System.Collections.Hashtable

Name              MemberType            Definition
----              ----------            ----------
Add               Method                void Add(System.Object key, System.Object value), void IDictionary.Add(System.Object key, System.Object value)
    .  .  .
Values            Property              System.Collections.ICollection Values {get;}

PS /> Get-Member -InputObject $iDictionary

   TypeName: System.Collections.Hashtable

Name              MemberType            Definition
----              ----------            ----------
Add               Method                void Add(System.Object key, System.Object value), void IDictionary.Add(System.Object key, System.Object value)
    .  .  .
Values            Property              System.Collections.ICollection Values {get;}

PS /> $iDictionary.GetType()

IsPublic IsSerial Name                  BaseType
-------- -------- ----                  --------
True     True     Hashtable             System.Object


PS /> $OrderedDictionary | Get-Member

   TypeName: System.Collections.Specialized.OrderedDictionary

Name              MemberType            Definition
----              ----------            ----------
Add               Method                void Add(System.Object key, System.Object value), void IDictionary.Add(System.Object key, System.Object value)
    .  .  .
Values            Property              System.Collections.ICollection Values {get;}

PS /> $OrderedDictionary.GetType()

IsPublic IsSerial Name                  BaseType
-------- -------- ----                  --------
True     True     OrderedDictionary     System.Object

Then, we get the IList based objects it changes, returning the members of the contents of the collection when piped to Get-Member. One must get the members of the collection itself through other means:

PS /> $Array | Get-Member

   TypeName: System.Int32

Name                 MemberType Definition
----                 ---------- ----------
CompareTo            Method     int CompareTo(System.Object value), int CompareTo(int value), int IComparable.CompareTo(System.Object obj), int         .  .  .
WriteLittleEndian    Method     int IBinaryInteger[int].WriteLittleEndian(byte[] destination), int IBinaryInteger[int].WriteLittleEndian(byte[] destination, int startIndex), int IBinaryInteger[int].WriteLittleEndian(System.Span[byte] destination)

   TypeName: System.String

Name                 MemberType            Definition
----                 ----------            ----------
Clone                Method                System.Object Clone(), System.Object ICloneable.Clone()
    .  .  .
Length               Property              int Length {get;}

PS /> Get-Member -InputObject $Array

   TypeName: System.Object[]

Name           MemberType            Definition
----           ----------            ----------
Add            Method                int IList.Add(System.Object value)
    .  .  .
SyncRoot       Property              System.Object SyncRoot {get;}

PS /> $Array.GetType()

IsPublic IsSerial Name                  BaseType
-------- -------- ----                  --------
True     True     Object[]              System.Array


PS /> $ArrayList | Get-Member

   TypeName: System.Int32

Name                 MemberType Definition
----                 ---------- ----------
CompareTo            Method     int CompareTo(System.Object value), int CompareTo(int value), int IComparable.CompareTo(System.Object obj), int IComparable[int].CompareTo(int other)
    .  .  .
WriteLittleEndian    Method     int IBinaryInteger[int].WriteLittleEndian(byte[] destination), int IBinaryInteger[int].WriteLittleEndian(byte[] destination, int startIndex), int IBinaryInteger[int].WriteLittleEndian(System.Span[byte] destination)

   TypeName: System.String

Name                 MemberType            Definition
----                 ----------            ----------
Clone                Method                System.Object Clone(), System.Object ICloneable.Clone()
    .  .  .
Length               Property              int Length {get;}

PS /> Get-Member -InputObject $ArrayList

   TypeName: System.Collections.ArrayList

Name           MemberType            Definition
----           ----------            ----------
Add            Method                int Add(System.Object value), int IList.Add(System.Object value)
    .  .  .
SyncRoot       Property              System.Object SyncRoot {get;}

PS /> $ArrayList.GetType()

IsPublic IsSerial Name                  BaseType
-------- -------- ----                  --------
True     True     ArrayList             System.Object


PS /> $List | Get-Member

   TypeName: System.Int32

Name                 MemberType Definition
----                 ---------- ----------
CompareTo            Method     int CompareTo(System.Object value), int CompareTo(int value), int IComparable.CompareTo(System.Object obj), int IComparable[int].CompareTo(int other)
    .  .  .
WriteLittleEndian    Method     int IBinaryInteger[int].WriteLittleEndian(byte[] destination), int IBinaryInteger[int].WriteLittleEndian(byte[] destination, int startIndex), int IBinaryInteger[int].WriteLittleEndian(System.Span[byte] destination)

   TypeName: System.String

Name                 MemberType            Definition
----                 ----------            ----------
Clone                Method                System.Object Clone(), System.Object ICloneable.Clone()
    .  .  .
Length               Property              int Length {get;}

PS /> Get-Member -InputObject $List

   TypeName: System.Collections.Generic.List`1[[System.Object, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]

Name           MemberType            Definition
----           ----------            ----------
Add            Method                void Add(System.Object item), void ICollection[Object].Add(System.Object item), int IList.Add(System.Object value)
    .  .  .
SyncRoot       Property              System.Object SyncRoot {get;}

PS /> $List.GetType()

IsPublic IsSerial Name                  BaseType
-------- -------- ----                  --------
True     True     List`1                System.Object

3

u/surfingoldelephant Aug 29 '24 edited Jul 26 '26

what it boils down to is that any collection where the type's ImplementedInterfaces includes [System.Collections.IDictionary] will return the collection members when piped to Get-Member, but any collection where the type's ImplementedInterfaces includes [System.Collections.IList] will return the collection items' members when piped to Get-Member.

IDictionary is indeed a hardcoded exception. PowerShell treats dictionaries (Collections.IDictionary, but not Collections.Generic.IDictionary`2) as scalar in enumeration contexts like the pipeline because key/value pairs typically make sense only as a single unit and not as individual elements.

On the flip side, PowerShell doesn't actually care if IList is implemented for it to enumerate a collection's elements. E.g., PSObject.Properties, whose type is PSMemberInfoIntegratingCollection`1, doesn't implement IList but is implicitly enumerated.

$foo = 'foo'.psobject.Properties
$foo -is [Collections.IList] # False
$foo.GetType().Name          # PSMemberInfoIntegratingCollection`1
$foo | Get-Member            # TypeName: System.Management.Automation.PSProperty

IEnumerable is what PowerShell primarily cares about for a type to be considered a "typical enumerable"/collection, but there are some hardcoded special-cases. These are the rules:

  • Must implement [Collections.IEnumerable] or be of type [Data.DataTable].
  • Must not be of type [string] or [Xml.XmlNode].
  • Must not implement [Collections.IDictionary].

If all rules are satisfied, enumeration is performed (in the pipeline, used in a foreach statement, used as the left-hand side operand of a comparison operator, etc). The rules can be found here and here.

LanguagePrimitives has methods to check this (reflection required in Windows PowerShell):

using namespace System.Management.Automation

$flags = [Reflection.BindingFlags] 'Static, NonPublic'
$isTypeEnumerable = [LanguagePrimitives].GetMethod('IsTypeEnumerable', $flags)
$isTypeEnumerable.Invoke($null, @{1 = 2}.GetType()) # False
$isTypeEnumerable.Invoke($null, 'a'.GetType())      # False
$isTypeEnumerable.Invoke($null, (1, 2).GetType())   # True 

# PS v6+, no reflection required.
[LanguagePrimitives]::IsObjectEnumerable('a')    # False 
[LanguagePrimitives]::IsObjectEnumerable((1, 2)) # True

# Less performant, but works in Windows PowerShell v5.1.
[LanguagePrimitives]::GetEnumerable('a') -is [Object] # False

1

u/sysiphean Aug 29 '24

Thank you. I kept banging around on IEnumerable as the key, but decided that couldn't be it because all the iDictionary types also were IEnumerable. I didn't consider that it was hard-coded in.

And I hadn't remembered that Xml.XmlNode isn't enumerable, but have run across that before.

1

u/sysiphean Aug 29 '24

Continued, because I went to long above...

So there you have it. If the Pipeline sees that type as one object, Get-Member gets piped the object itself. If the Pipeline sees that type as a collection of objects, Get-Member gets piped the objects inside that object. Which, for the record, is spoken to in the Help...

PS /> Get-Help Get-Member -Parameter InputObject

-InputObject <PSObject>
    Specifies the object whose members are retrieved.

    Using the InputObject parameter is not the same as piping an object to Get-Member . The differences are as follows:

    - When you pipe a collection of objects to Get-Member , Get-Member gets the members of the individual objects in
        the collection, such as the properties of each string in an array of strings. - When you use InputObject to submit
        a collection of objects, Get-Member gets the members of the collection, such as the properties of the array in an
        array of strings.

    Required?                    false
    Position?                    named
    Default value                None
    Accept pipeline input?       True (ByValue)
    Accept wildcard characters?  false

Oh, if you want some real fun, look at the difference in these:

@(@{}) | Get-Member
@(1,"2") | Get-Member
@() | Get-Member
@(@()) | Get-Member
@(1,@()) | Get-Member