Home > Back-end >  Powershell Random selection and count
Powershell Random selection and count

Time:05-27

I'm trying to write a powershell script that picks up from an array 10 random items, list them and then writes which one was picked the most and how many times.

I have this:

for ($num = 1 ; $num -le 10 ; $num  ){
$namelist = @(
    "Item 1",
    "Item 2",
    "Item 3",
    "Item 4",
    "Item 5"
)
Get-Random -InputObject $NameList
}

As result it shows me 10 picks from the list, but everytime I need to count which one was picked the most.

Anyone can help?

CodePudding user response:

You can combine Group-Object with Sort-Object:

$namelist = @(
    "Item 1"
    "Item 2"
    "Item 3"
    "Item 4"
    "Item 5"
)

& {
    for ($num = 1 ; $num -le 10 ; $num  ) {
        Get-Random -InputObject $NameList
    }
} | Group-Object -NoElement | Sort-Object Count -Descending

This would return an array of objects, if you wanted to see which one was picked the most you can pipe it into Select-Object -First 1.

If you don't want to use Group-Object for some reason, you can also accomplish this using a hash table:

$map = @{}
for ($num = 1 ; $num -le 10 ; $num  ) {
    $pick = Get-Random -InputObject $NameList
    $map[$pick] = 1   $map[$pick]
}
$map.GetEnumerator() | Sort-Object { $_.Value } -Descending
  • Related