PoshCode Archive  Artifact Content

Artifact 4ebb4e356c11cf91376ac0a2e4a37b1795faae506575bf5be4425fa8be272d99:

  • File Select-Random.ps1 — part of check-in [39b5baf902] at 2018-06-10 14:05:49 on branch trunk — Selects a random element from the collection either passed as a parameter or input via the pipeline. (user: unknown size: 1079)

# encoding: ascii
# api: powershell
# title: Select-Random
# description: Selects a random element from the collection either passed as a parameter or input via the pipeline.
# version: 0.1
# license: CC0
# x-poshcode-id: 60
# x-derived-from-id: 81
# x-archived: 2008-10-05T09:05:53
#
#
param([array]$Collection)
 
begin {
    $result = $Seed
    
    if ($args -eq '-?') {
        ''
        'Usage: Select-Random [[-Collection] <array>]'
        ''
        'Parameters:'
        '    -Collection : The collection from which to select a random entry.'
        '    -?          : Display this usage information'
        ''
        'Examples:'
        '    PS> $arr = 1..5; Select-Random $arr'
        '    PS> 1..5 | Select-Random'
        ''
        exit
    } 
 
    $coll = @()
    if ($collection.count -gt 0) { 
        $coll += $collection
    }
}
 
process {
    if ($_) {
        $coll += $_;
    }
}
 
end {
    if ($coll) {
        $randomIndex = Get-Random -Min 0 -Max ($coll.Count)
        $coll[$randomIndex]
    }
}