22

I am trying to declare List in PowerShell, where the Person is defined using Add-Type:

add-type -Language CSharpVersion3 -TypeDefinition @"
    public class Person
    {
        public Person() {}

        public string First { get; set; }
        public string Last { get; set; }
    }
"@ 

This works fine:

New-Object Person
New-Object System.Collections.Generic.List``1[System.Object]

But this line fails:

New-Object System.Collections.Generic.List``1[Person]

What is wrong here?

1
  • 1
    For anyone else wondering, the line that fails (above) works in Powershell 3.0 (although i needed to remove "-Language CSharpVersion3" because I ran this on Windows Server 2012). Commented Jun 21, 2013 at 23:53

2 Answers 2

38

This is a bug in New-Object. This will help you create them more easily: http://www.leeholmes.com/blog/2006/08/18/creating-generic-types-in-powershell

UPDATE: PowerShell added support for this in Version 2:

PS > $r = New-Object "System.Collections.Generic.List[Int]"
PS > $r.Add(10)
Sign up to request clarification or add additional context in comments.

1 Comment

Welcome to StackOverflow Lee!
9

Well, I was trying to create a list of FileStream objects and this was my solution (based on this link -- which actually describes a way to solve your problem):

$fs = New-Object 'System.Collections.Generic.List[System.IO.FileStream]'
$sw = New-Object 'System.Collections.Generic.List[System.IO.StreamWriter]'
$i = 0
while ($i < 10)
{
    $fsTemp = New-Object System.IO.FileStream("$newFileName",[System.IO.FileMode]'OpenOrCreate',[System.IO.FileAccess]'Write')
    $fs.Add($fsTemp)
    $swTemp = New-Object System.IO.StreamWriter($fsTemp)
    $sw.Add($swTemp)
    $i++
}

Hope that helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.