Powershell Foreach 循环遍历字典并将结果传送到另一个字典。我可以使用 for 循环,& 在 python 中使用 foreach 但不能使用 powershell

Powershell Foreach loop through dictionary with results to another dictionary. I can do with for loop, & in python with foreach but not powershell

$scores = [ordered]@{
Jack = 81;
Mike = 78;
Mark = 99;
Jim = 64;
}

$grades = [ordered]@{}

$len = $scores.Count
for ($n=0;$n -lt $len; $n++){
    if ($($scores.values)[$n] -gt 65){
        $grades += @{$($scores.keys)[$n] = $($scores.keys)[$n]}
        $grades[$n] = $($scores.values)[$n] = "PASS"
    }
else{
    $grades += @{$($scores.keys)[$n] = $($scores.keys)[$n]}
    $grades[$n] = $($scores.values)[$n] = "FAIL"
}
}

$grades

=======以上在 POWERSHELL 中工作得很好

*****下面是 POWERSHELL 中的问题(此结构在 Python 中有效)

$scores = [ordered]@{
Jack = 81;
Mike = 78;
Mark = 99;
Jim = 64;

}

$grades = [ordered]@{}

foreach($key in $scores){
    if ($scores[$key] -gt 65){
        $grades[$key] = "PASS"
    }
    else{
        $grades[$key] = "FAIL"
    }
}

$grades

======== 下面是正确的 FOR 循环输出:

******** 这是 FOREACH 的输出:

请告诉我 FOREACH 循环是如何失败的。

(对 FOR 循环的任何改进都是锦上添花!)

缺少 foreach 示例 .Keys (recommended to use .PSBase.Keys) or .GetEnumerator() 以便枚举它:

$scores = [ordered]@{
    Jack = 81
    Mike = 78
    Mark = 99
    Jim  = 64
}

# - Using `.PSBase.Keys`

$grades = [ordered]@{}
foreach($key in $scores.PSBase.Keys) {
    if ($scores[$key] -gt 65) {
        $grades[$key] = "PASS"
        continue
    }
    $grades[$key] = "FAIL"
}

# - Using `.GetEnumerator()`

$grades = [ordered]@{}
foreach($pair in $scores.GetEnumerator()) {
    if ($pair.Value -gt 65) {
        $grades[$pair.Key] = "PASS"
        continue
    }
    $grades[$pair.Key] = "FAIL"
}