Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell . Declare generic list with class defined using 'Add-Type'

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?

like image 264
alex2k8 Avatar asked Mar 27 '09 01:03

alex2k8


2 Answers

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)
like image 191
LeeHolmes Avatar answered Oct 19 '22 02:10

LeeHolmes


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!

like image 41
Girardi Avatar answered Oct 19 '22 02:10

Girardi