2010-07-23 70 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

相關問題