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.
- 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]
- }
- }
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.
PowerShell Code Repository