1

PowerShell version 5 introduced the Class keyword, making it easier to create custom classes in PowerShell. The announcement only provides a brief summary on properties:

All properties are public. Properties require either a newline or semicolon. If no object type is specified, the property type is object.

So far so good. Which means that I can create a class that looks like this with ease:

Class Node
{
    [String]$Label
    $Nodes
}

Where I run into problems is that by not specifying a type for $Nodes it defaults to System.Object. My goal is to use a System.Collections.Generic.List type, but thus far have not figured out how to do so.

Class Node
{
    [String]$Label
    [System.Collections.Generic.List<Node>]$Nodes
}

The above results in a whole litany of issues:

At D:\Scripts\Test.ps1:4 char:36
+     [System.Collections.Generic.List<Node>]$Nodes
+                                    ~
Missing ] at end of attribute or type literal.
At D:\Scripts\Test.ps1:4 char:37
+     [System.Collections.Generic.List<Node>]$Nodes
+                                     ~
Missing a property name or method definition.
At D:\Scripts\Test.ps1:4 char:5
+     [System.Collections.Generic.List<Node>]$Nodes
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Missing closing '}' in statement block or type definition.
At D:\Scripts\Test.ps1:5 char:1
+ }
+ ~
Unexpected token '}' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : EndSquareBracketExpectedAtEndOfAttribute

Which leads me to my question how do I make use of a generic type for a property in PowerShell 5?

ahsteele
  • 26,243
  • 28
  • 134
  • 248

1 Answers1

4

While crafting my question I stumbled across an answer which details how to create Dictionary objects in PowerShell 2:

$object = New-Object 'system.collections.generic.dictionary[string,int]'

Of particular note is the lack of the use of < and > for generic declaration instead using [ and ]. Switching my class declaration to use square brackets instead of angle brackets solved my problem:

Class Node
{
    [String]$Label
    [System.Collections.Generic.List[Node]]$Nodes
}
Community
  • 1
  • 1
ahsteele
  • 26,243
  • 28
  • 134
  • 248