2010-01-21 62 views
13

我该如何在PowerShell 2中创建一个列表? 我试着这些:
PowerShell 2中的泛型不起作用?

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


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

和我得到的只是什么都没有。出了什么问题?

我运行XP SP3,如果它的事项

回答

18

试试这个:

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 
+0

我也无法得到这一个工作,没有任何回报。它应该工作吗? – Parsa 2010-01-21 17:04:33

+0

如果你使用的是PowerShell 2.0,它应该。 – 2010-01-21 17:19:55

+0

现在,我想通了,这些尝试都没问题,问题是PS正在显示数据,所以它什么都不显示,谢谢。 – Parsa 2010-01-21 17:27:44

3

如果试图创建一个基于字符串列表,试试这个:

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

请注意,您必须指定“system.string” (至少在我的比赛中))。如果你只是使用'string',它会抛出一个异常。

[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 
+0

没有运气,我就是用这个语法在PowerShell中1,但现在并没有在PS2返回任何东西,这就是为什么我试图使用激活的原因类。 – Parsa 2010-01-21 16:21:14

+0

这是什么意思“它不返回任何东西”?什么是错误信息 – stej 2010-01-22 09:45:37

+2

当收集为空时,它什么都不输出。这种类型给你的印象是,新对象实际上失败了。 – 2010-01-22 23:30:53