PoshCode Logo PowerShell Code Repository

Select-Random (modification of post by view diff)
View followups from Joel Bennett | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/60"></script>download | new post

Selects a random element from the collection either passed as a parameter or input via the pipeline.

  1. param([array]$Collection)
  2.  
  3. begin {
  4.     $result = $Seed
  5.    
  6.     if ($args -eq '-?') {
  7.         ''
  8.         'Usage: Select-Random [[-Collection] <array>]'
  9.         ''
  10.         'Parameters:'
  11.         '    -Collection : The collection from which to select a random entry.'
  12.         '    -?          : Display this usage information'
  13.         ''
  14.         'Examples:'
  15.         '    PS> $arr = 1..5; Select-Random $arr'
  16.         '    PS> 1..5 | Select-Random'
  17.         ''
  18.         exit
  19.     }
  20.  
  21.     $coll = @()
  22.     if ($collection.count -gt 0) {
  23.         $coll += $collection
  24.     }
  25. }
  26.  
  27. process {
  28.     if ($_) {
  29.         $coll += $_;
  30.     }
  31. }
  32.  
  33. end {
  34.     if ($coll) {
  35.         $randomIndex = Get-Random -Min 0 -Max ($coll.Count)
  36.         $coll[$randomIndex]
  37.     }
  38. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me