Home > Enterprise >  How can I collate values from a hashtable and turn them into percentages?
How can I collate values from a hashtable and turn them into percentages?

Time:02-14

In PowerShell, I am generating hashtables where the value of a key is an integer, but this needs to be converted into a percentage with respect to the other key-value pairs. Consider the following hashtable:

enter image description here

There are a total of 4 key-value pairs here. However, only QuestionSet1ARL has a value of something other than 0. I therefore want to report that QuestionSet1ARL has a value of 100%. Below is a slightly different example:

enter image description here

Here, both QuestionSetTrust and QuestionSet4 have values of 5. They therefore makeup 50% of the values in the hashtable. If the value of QuestionSetTrust was 2 and QuestionSet4 was 1, the percentages would be 66% and 33% respectively.

I think Ill need to create a secondary hashtable (enabledSurveys) to do this (one that only contains the key-value pairs where the value was greater than 0. To do this, I have written a simple loop:

foreach ($survey in $initialSurveys.Keys) { 
        # Set the ratio variable equal to the value from the hashtable. For ease of reading.
        $surveyRatio = $initialSurveys.$survey
        if ($surveyRatio -gt 0) {
            $enabledSurveys.add($survey, $surveyRatio)
        }
    }

I think I then need to sum the values to achieve a total, and then derive contributedTotal from each of the keys. Before I continue, is there a more intuitive way to derive this information without the need for a second hashtable?

Optimal outcome:

enter image description here

CodePudding user response:

A total sum of the values is needed in order to determine percentage.

$InitialSurveys = @{
    'QuestionSetTrust' = 1
    'QuestionSet4' = 5
}
$Total = 0
foreach ($Key in $InitialSurveys.Keys) {
    $Total  = $InitialSurveys[$Key]
}
$ResultHash = @{}
foreach ($Key in $InitialSurveys.Keys) {
    $ResultHash[$Key] = "{0}%" -f "$([math]::Round(($InitialSurveys[$Key] / $Total * 100.0), 2))"
}
$ResultHash
  • Related