在PowerShell中,在对哈希表进行迭代时修改哈希表可以吗?

在PowerShell中,在对哈希表进行迭代时修改哈希表可以吗?,powershell,hashtable,Powershell,Hashtable,代码如下: $hash.GetEnumerator() | %{ if($_.value.x -eq $null) { $hash.remove($_.name); } } 如您所见,它在对哈希表进行迭代时会修改哈希表。这样好吗? 谢谢。我在PowerShell 2.0上尝试了以下功能: $hash = @{"A1"="rouge";"A2"="vert";"A3"="bleu"} $hash.GetEnumerator() | % { if($_.va

代码如下:

$hash.GetEnumerator() | %{
    if($_.value.x -eq $null)
    {
        $hash.remove($_.name);
    }
}
如您所见,它在对哈希表进行迭代时会修改哈希表。这样好吗?
谢谢。

我在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
psc:\>$h=@{“a”=1;“b”=2;“C”=3;“d”=4}
PS C:\>$h.GetEnumerator()|%{
>>如果($\u0.Value-eq 2){$h.Remove($\u0.Name)}
>>“{0}:{1}”-f$\名称,$\值
>> }
>>
a:1
b:2
枚举集合时出错:集合为
被改进的;枚举操作可能无法执行。。
第1行字符:1
+
$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
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