Freigeben über


Random things with Get-Random

Today's post is less about anything in particular than it is about jotting a few things down for personal reference.

I learned a couple of things over the last week while developing a tool. I'm sure I learned them once before, but as a person with finite storage and recall capacity, this tidbits were replaced by something I perceived to be of more timely import at the time (such as my kids' birthday gifts, picking up a suit at the cleaners, a really great Detroit style pizza recipe I've finally put the finishing touches on, and how I've recently become a fan of grass-fed butter (well, technically butter made from milk produced by grass-fed cows, since you can't really get butter to eat anything successfully)).

So, without further ramblings ...

Using Get-Random with an array input object

Since I haven't found a great PowerShell-only tool to generate Lorem Ipsum text (yes, I'm aware of the module in the PowerShell gallery, but found it lacked some of the finesse that I wanted), I decided to create one (the creation of necessity for another tool I'm working on).  So, here's a simplified snippet of how I used Get-Random with a word list to create a string of text:

 PS> $LoremIpsumText = @('lorem','ipsum','dolor','set','amit','do','preactus','coloron','duchartes','rampunct','finialis','rufrum')
PS> ((1..10) | % { Get-Random -InputObject $LoremIpsumText }) -join " "
lorem set ipsum preactus do ipsum do dolor set dolor

Pretty nifty.  If you didn't follow along:

  • (1..10) - A short-hand way to run a loop n number of times, incrementing by 1 each pass
  • Get-Random -InputObject $LoremIpsumText - Instead of using -MininumValue and -MaximumValue or -SetSeed parameters for integer results, we can tell the cmdlet to use the values stored in $LoremIpsumText to be used a pool of values from which to pull
  • -join " " - Let's just join them together with a space character

Using Get-Random to select a boolean value

Then, I wanted to find a way to select randomly between True and False.  So, I tried a few things, and landed on this:

 Get-Random -InputObject ([bool]$True,[bool]$False)

You can, of course, capture the result to a variable, which means you've now created a random(ish) boolean value.

Making a coin-flipper

Of course, now that you know you can use PowerShell to create a random(ish) True/False generator, you're probably dying for ways to apply this in your daily life.

I know I was.

So, have no fear, I've got a quick little way for you to now run a function to call heads or tails. Call it your own two-face app.

 function CoinFlip
{
 $Result = Get-Random -InputObject @([bool]$True, [bool]$False)
 switch ($Result)
 {
 True { "Heads" }
 False {"Tails" }
 }
}

Whenever you need to choose between two restaurants, you can now pause the decision-making process, pull out your trusty CoinFlip function and leave the decision to fate and the will of Jeffrey Snover.

Or tacos.  Always tacos.