views:

325

answers:

2

How could I make a List in PowerShell 2? I've tried these:

[activator]::createinstance(([type]'system.collections.generic.list`1').makegenerictype([string]))

and

[activator]::createinstance(([type]'system.collections.generic.list`1').makegenerictype([string]))

and all I get is just nothing. What's going wrong?

I'm running XP SP3, if it matters

+1  A: 

If you try to create a list based on strings, try this:

New-Object 'System.Collections.Generic.List[system.string]'

Note that you have to specify 'system.string' (at least on my comp ;) ). If you just use 'string', it throws an exception.

[61]: New-Object 'System.Collections.Generic.List[string]'
New-Object : Cannot find type [System.Collections.Generic.List[string]]: make sure the assembly containing this type is loaded.
At line:1 char:11
+ New-Object <<<<  'System.Collections.Generic.List`1[string]'
    + CategoryInfo          : InvalidType: (:) [New-Object], PSArgumentException
    + FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand
stej
No luck, I was using this syntax in PowerShell 1, but now it doesn't return anything in PS2, this is the reason why I tried to use the Activator class.
Parsa
what does it mean "it doesnt return anything"? what is the error message
stej
When the collection is empty, it outputs nothing. Kind of gives you the impression that the new-object failed when in fact it worked.
Keith Hill
+3  A: 

Try this:

PS> $list = New-Object 'System.Collections.Generic.List[string]'
PS> $list.Add('foo')
PS> $list
foo

PS> $d = New-Object 'System.Collections.Generic.Dictionary[string,datetime]'
PS> $d.Add('moonshot', [datetime]'7/20/1969')
PS> $d['moonshot']

Sunday, July 20, 1969 12:00:00 AM
Keith Hill
I can't get this one work either, returns nothing. Should it work?
Parsa
If you are on PowerShell 2.0 it should.
Keith Hill
Now, I figured out, these attempts were all right, problem was the PS was displaying the data, so it would display nothing, thank you.
Parsa
This works except when the generic type resides in a different assembly. Then I get the error 'make sure the assembly containing this type is loaded'. And the type assembly is loaded, a New-Object of the same type works fine.
Bernard Vander Beken