2010-07-23 69 views
11

我想在PowerShell脚本中使用HashSet。我想我已经找到了如何做实例化泛型集合对象:可以在PowerShell中使用System.Core.dll/System.Collections.Generic.HashSet吗?

[type] $strType = "string" 
$listClass = [System.Collections.Generic.List``1] 
$listObject = $base.MakeGenericType(@($t)) 
$myList = New-Object $setObject 

这工作正常列表和字典,但是当我尝试创建一个HashSet的,我得到:

Unable to find type [System.Collections.Generic.HashSet`1]: make sure that the assembly containing this type is loaded. 

所以它看起来像现在我需要加载System.Core.dll,但我似乎无法得到加载该程序集的PowerShell。例如主叫[System.Reflection.Assembly] :: LoadWithPartialName( “System.Core程序”)导致该异常:

"LoadWithPartialName" with "1" argument(s): "Could not load file or assembly 'System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified." 

任何指针?

+0

你在PowerShell中v1或v2? – x0n 2010-07-23 18:56:52

+0

我在Win2k8 R2上,并得到主机说版本2.0 – nick 2010-07-23 19:11:34

+2

可能的重复:请参阅答案http://stackoverflow.com/questions/184476/powershell-generic-collections – zdan 2010-07-23 19:18:03

回答

21

的PowerShell 2.0使得1这更容易)将添加型cmdlet的加载组件和2)更新到语法,以指定一个封闭泛型类型名称简单如:

PS> Add-Type -AssemblyName System.Core 
PS> $h = new-object 'System.Collections.Generic.HashSet[string]' 
PS> $h.Add('f') 
True 
+0

伟大的工程 - 谢谢。 – nick 2010-07-23 19:45:32

+0

然后我可以通过执行'[Parameter(Mandatory = $ true)] [hashset]'来指定参数类型吗? – 2015-03-10 15:55:31

+2

是的,但您需要指定参数类型为'[Collections.Generic.HashSet [string]]'替代字符串您需要存储在哈希集中的类型。 – 2015-03-10 16:00:40

相关问题