Let's have a little fun with St. Patrick's Day and perhaps even learn a little PowerShell.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
Imagine, and this might be hard I know, that you are in a bar on St. Patrick's Day with a friend. But you can't think of what to order. Or perhaps you've been there too long and can't make a rational decision. Fortunately you can still run a simple PowerShell script on your netbook.
[cc lang="PowerShell"]
#requires -version 2.0
#define an array of beverage choices
$drinks=@(
"beer","Guiness","milk",
"rootbeer","whiskey",
"water","wine cooler",
"porter","ale","hard lemonade",
"chablis","shot")
#get two random elements from the array
$choice=$drinks | get-random -count 2
#choice is also an array. I'll make my drink order the first element
$mydrink=$choice[0]
#my friend get's the second element.
$yourdrink=$choice[1]
#construct a string message using the -f operator
$msg="I'll take another {0} and a nice {1} for my friend." -f $mydrink,$yourdrink
#display the message
Write-Host $msg -ForegroundColor Green
[/cc]
The script defines an array of drink choices. Using the @() construct is an explicit way of defining an array. I could have easily used a comma separated list of strings. The main part of the script is deciding what to drink. The drink array is piped to the Get-Random cmdlet which returns a 2 values. The $choice variable is also an array. I use the [] to reference an element by index number. I'll assign the first element, always start at 0, to my drink order and the second element to my friend's.
Next I need to construct a string. In this example I wanted to use the -f format operator. This is a great technique when you need to construct complex strings with variables. Don't try to concatenate. The place holders like {0}, will be replaced with the correponding value on the right side of the -f operator.
All that's left is to place my order. I use Write-Host which only writes to the console., which is fine for my purposes. Although, as an added bonus I could take advantage of the terrific text to speech engine in Windows 7 and also "speak" my order to the bartender.
[cc lang="PowerShell"]
#optionally speak it
$Voice=New-Object -ComObject "SAPI.SPVoice"
$voice.speak($msg) | out-Null
[/cc]
The $voice object has a few other properties you can tweak. Pipe the object to Get-Member to see for yourself. By the way, I pipe the output from the Speak() method to Out-Null to suppress the integer output.
If you'd like to try this out, download BarOrder.ps1.