I like to have fun with PowerShell, as is hopefully evident with this Friday Fun serious, and today that is especially true. Perhaps you need a quick break from the end of the week grind. Or maybe you want to learn something new about PowerShell. Hopefully today's fun will meet both requirements. Today's fun will include XML, scope and Switch. Let's rock.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
If you haven't figured it out, rock 'n roll is the theme for today. I have put together a little rock and roll quiz. In many rock bands there's at least one member is well known. If someone says "Axl Rose" you most likely will know Guns n' Roses. But would you recognize the other members of the band? I created an XML document with a number of well known rock bands. Because band members change, I tried to use the line ups from the bands peak years. If you want to play you will need to download BandData.xml. Save as an XML file to same directory as the script, which I'll show you in a moment. Try not to peek too much at the contents. This is the structure.
<Bands> <Band> <Name></Name> <Lead></Lead> <Members> <Member></Member> <Member></Member> </Members> </Band> </Bands>
My quiz is a PowerShell script that processes the data in the XML document. It will display a list of band members, without the recognizable lead and multiple choice of possible bands. After answering the questions you will be judged, I mean graded.
#BandQuiz.ps1 Param($Questions = 10) $file = '.\BandData.xml' [xml]$data = Get-Content $file #get all of the band names $bandNames = $data.Bands.Band.name #select 10 random entries $testdata = $data.Bands.band | Get-Random -Count $Questions #initialize some counter variables that will be updated from a different scope $script:i = 0 $script:q = 0 #process each one foreach ($band in $testdata) { #build a list of band names $answer = $band.name $Choices = $bandNames | where {$_ -ne $answer} | Get-Random -count 3 $Choices+= $answer #sort names and create a hashtable using a number as the key $bandhash = @{} $choices | Sort | foreach -begin {$K=1} -process { $bandhash.Add($K,$_) $K++ } #get band members as a string list $members = ($band.members | select -expand member | Format-List | Out-String).Trim() #prompt #use a scriptblock as an ad-hoc function $promptblock = { Param([string]$Lead) if ($lead) {$leadmember = "*$lead*`n"} #cls $script:Q++ #define a here string to be used for the prompt $prompt=@" Question: $script:Q $members $leadmember What band do these people belong to?" $(($bandHash.GetEnumerator() | Sort Name | out-string).trim()) Enter a number or 0 to see the lead band member "@ [int]$r = Read-Host -Prompt $prompt #check result if ($r -eq 0) { $Band.lead #decrement question counter since we're repeating $script:Q-- #re-run the prompt scriptblock to include the lead member &$promptblock -lead $band.Lead } elseif ($bandhash.$r -eq $answer) { Write-Host "Correct!" -ForegroundColor green #record result $script:i++ } else { Write-Host "Incorrect" -ForegroundColor red } } #close promptblock &$promptblock } #display results [int]$correct = ($i/$Questions) * 100 Switch ($correct) { {$_ -ge 90} {$quip = "You are a juke box hero." ; break} {$_ -ge 75} {$quip = "You're bad to the bone." ; break} {$_ -ge 50} {$quip = "It's a long way to the top if you wanna rock 'n roll." ; break} {$_ -ge 25} {$quip = "Another one bites the dust." ; break} default {$quip = "Stick to Mantovani."} } "`nYou got {0:P0} correct. {1}" -f ($i/$Questions),$Quip
Let's look at a few key points of the script.
First, I need to load the XML document.
$file = '.\BandData.xml' [xml]$data = Get-Content $file
The [XML] type accelerator will create an XML document. When you have an XML document in PowerShell, each node can be treated like a property so it is very easy to navigate or get values, like a list of all the band names.
$bandNames = $data.Bands.Band.name
The script then selects a random number of band entries from the XML document. These will be the basis of the quiz. For each item I create a list of band choices and band members that will be displayed. You'll also noticed that I initialize some counters with the $script prefix.
$script:i = 0 $script:q = 0
Here's why. I am using a scriptblock, defined as $promptblock, to display each question and keep track of correct answers. The scriptblock runs in a new scope, or container. That means when it tries to do something with a variable like $Q it first looks in the current scope for that item. If it finds it, it uses it. Otherwise PowerShell searches up the scope hierarchy to the parent scope looking for the item. But here's what trips people up. If you are only reading, like I am, for things like the $bandhash object, PowerShell will happily find it in the parent scope and display it. But when I try to modify a variable like $Q or $i it can only modify it in the current scope. But I need to use those variables outside of the scriptblock scope, so I preface the variable with $Script: to indicate the scope level for those variables. The general rule is to not reference out-of-scope variables, but since I'm using $script: I'm telling PowerShell I know what I'm doing.
After running through all the questions, the script can calculate how many correct answers you had and present a score card. I decided to use a Switch statement to assist.
Switch ($correct) { {$_ -ge 90} {$quip = "You are a juke box hero." ; break} {$_ -ge 75} {$quip = "You're bad to the bone." ; break} {$_ -ge 50} {$quip = "It's a long way to the top if you wanna rock 'n roll." ; break} {$_ -ge 25} {$quip = "Another one bites the dust." ; break} default {$quip = "Stick to Mantovani."} }
Normally in a Switch you would use a simple value. But you can also use PowerShell expressions. In my Switch statement, if the value of $Correct is >= 90, then I assign a certain value to $quip. When using expressions, use $_. Remember that Switch will process every matching expression and since I don't want that, I'm using the Break keyword so PowerShell knows not to keep checking the other possibilities.
When you run the quiz, you will get an item like this:
The display is from the prompt scriptblock. If you need a little help, enter 0 which re-displays the question this time with the (hopefully) more recognizable lead.
And the final snarky commentary on your rock knowledge.
Because I am of a certain age, the contents of my band data xml file might be slightly skewed. If you were born after 1985 you might have some problems.
I think XML files scare some IT Pros but they really aren't that difficult to work with once you understand some basics. In fact, I'll be coming back to my band xml file in future posts. In the mean time, party on and let me know if you have any questions about my quiz script.
Awesome