2009-10-20 34 views

回答

8

請嘗試以下

$table = new-object System.Collections.Hashtable 
for ($i = 0; $i -lt $list.Length; $i += 2) { 
    $table.Add($list[$i],$list[$i+1]); 
} 
+4

我想我希望有一些更簡潔的東西 –

2

如何:

$ht = @{} 
$key = ""; 
("Key",5,"Key2",6) | foreach ` 
{ 
    if($key) 
    { 
     $ht.$key = $_; 
     $key=""; 
    } else 
    {$key=$_} 
} 
+1

我喜歡這一點,但你可以簡化一下: $ ht = @ {}; $ key = 0 「Key」,5,「Key2」,6 | foreach {if($ key){$ ht。$ key = $ _; $ key = 0} else {$ key = $ _}} –

+0

注意,註釋格式化程序在「Key」之前吃掉了我的換行符。 。 –

+0

謝謝。我想這是少打字。 – zdan

2
$h = @{} 
0..($l.count - 1) | ? {$_ -band 1} | % {$h.Add($l[$_-1],$l[$_])} 

$h = @{} 
0..($l.count - 1) | ? {$_ -band 1} | % {$h.($l[$_-1]) = $l[$_]} 

$h = @{} 
$i = 0 
while ($i -lt $l.count) {$h.Add($l[$i++],$l[$i++])} 
11
Function ConvertTo-Hashtable($list) { 
    $h = @{} 

    while($list) { 
     $head, $next, $list = $list 
     $h.$head = $next 
    } 

    $h 
} 

ConvertTo-Hashtable ("Key",1,"Key2",2) 
+1

另請參閱Bruce Payette的文章:[PowerShell提示:如何「移動」陣列...](http://blogs.msdn.com/b/powershell/archive/2007/02/06/powershell-tip-how -to-shift-arrays.aspx) –

+3

是的。此外,這是功能世界的標準模式。 可以縮短到 而($頭,$下,$列表= $列表){$ 小時。$頭= $下 } –

+0

洛夫該溶液中。 – craig

1

如果您KeyValuePairs,是明確 'Microsoft.Azure.Management.WebSites.Models.NameValuePair',那麼你可以使用:

Function ConvertListOfNVPTo-Hashtable($list) { 
    $h = @{} 
    $list | ForEach-Object { 
     $ht[$_.Name] = $_.Value 
    } 
    return $h 
}