在PowerShell中,在迭代时修改哈希表是否合适?

时间:2013-07-24 06:52:11

标签: powershell hashtable

这是代码:

$hash.GetEnumerator() | %{
    if($_.value.x -eq $null)
    {
        $hash.remove($_.name);
    }
}

如您所见,它在迭代时修改哈希表。这样好吗? 感谢。

2 个答案:

答案 0 :(得分:1)

我在PowerShell 2.0上试试这个:

$hash = @{"A1"="rouge";"A2"="vert";"A3"="bleu"}
$hash.GetEnumerator() | % { if($_.value -eq "bleu") {$hash.remove($_.name)}}

它给出了:

Une erreur s'est produite lors de l'énumération parmi une collection : La collection a été modifiée ; l'opération d'énumérat
ion peut ne pas s'exécuter..
Au niveau de ligne : 1 Caractère : 1
+  <<<< $hash.GetEnumerator() | % { if($_.value -eq "bleu") {$hash.remove($_.name)}}
    + CategoryInfo          : InvalidOperation: (System.Collecti...tableEnumerator:HashtableEnumerator) [], RuntimeExceptio
   n
    + FullyQualifiedErrorId : BadEnumeration

原因是尝试在枚举时修改集合,抛出异常。您可以尝试使用“for”语句。

如果您想使用foreach语句,可以尝试:

$hash = @{"A1"="rouge";"A2"="vert";"A3"="bleu"}
[string[]]$t = $hash.Keys
$t |  % { if($hash[$_] -eq "vert") {$hash.remove($_)}}
$hash

Name                           Value
----                           -----
A3                             bleu
A1                             rouge

答案 1 :(得分:0)

PS C:\> $h = @{ "a"=1; "b"=2; "c"=3; "d"=4 }
PS C:\> $h.GetEnumerator() | % {
>> if ($_.Value -eq 2) { $h.Remove($_.Name) }
>> "{0}: {1}" -f $_.Name, $_.Value
>> }
>>
a: 1
b: 2
An error occurred while enumerating through a collection: Collection was
modified; enumeration operation may not execute..
At line:1 char:1
+  <<<< $h.getenumerator() | % {
    + CategoryInfo          : InvalidOperation:
      (System.Collecti...tableEnumerator:HashtableEnumerator) [],
      RuntimeException
    + FullyQualifiedErrorId : BadEnumeration

在发布问题之前进行简单的测试真的很难吗?

相关问题