Home > Software engineering >  Powershell Foreach loop through dictionary with results to another dictionary. I can do with for loo
Powershell Foreach loop through dictionary with results to another dictionary. I can do with for loo

Time:03-26

$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

=======THE ABOVE WORKS IN POWERSHELL JUST FINE

*******BELOW IS THE PROBLEM IN POWERSHELL (This structure works in 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

======== Here is the correct FOR loop output:Expected Output from For

******** Here is the output from FOREACH:Current Output from Foreach

Please show me how the FOREACH loop is failing.

(Any improvement on the FOR loop is frosting on the cake!)

CodePudding user response:

The foreach example is missing either .Keys (recommended to use .PSBase.Keys) or .GetEnumerator() in order to enumerate it:

$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"
}
  • Related