r/PowerShell • u/bseab1024F • 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.
View all comments
Show parent comment
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 toGet-Member, but any collection where the type's ImplementedInterfaces includes[System.Collections.IList]will return the collection items' members when piped toGet-Member. (I did not check all 74iDictionaryimplementing types, all 108iListones, or any of the 109 that implement neither but do implementiCollection, 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
IDictionaryandIList. First off, I built the typed objects, filled with oneInt32and oneString, with or without a key as needed: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
iDictionarybased objects, which do work as you said, returning the members of the collection itself when piped toGet-Member.In all these examples, I removed all but the first and last members for clarity.
Then, we get the
IListbased objects it changes, returning the members of the contents of the collection when piped toGet-Member. One must get the members of the collection itself through other means: