This continues my series of solution posts for the 2008 Scripting Games with my solution for the Beginner’s Event 7 and
Beginner’s Event 8. I’m wrapping them together because beginner’s event 7 was just a debugging exercise so I just pasted the solution at the bottom1.
Event 8 was the age old “Higher or Lower” guessing game: the script picks a random number between 1 and 50 and then lets the user guess at it. After each guess, you tell them whether their guess was low or high, and when they guess it you tell them they got it, and how many guesses it took.
$r = new-object Random
$answr = $r.Next(1,51)
$count = 0
while(++$count) {
switch($answr.CompareTo([int](Read-Host "Enter a number between 1 and 50"))) {
1 { "Too Low" }
-1 { "Too High" }
0 { return "The number was: $answr`nIt took you $count guesses" }
}
}
It’s a pretty simple script, and the only part that I thought was cool was the way I used the while loop to increment the counter (it’s important to PRE-increment it, so it’s not equal to 0 the first time it’s tested). I used the switch statement so that I wouldn’t need to store the user’s guess. Nothing to be proud of, nothing to really point out. If you didn’t know how to get a random number in .Net, the Next method of the Random object takes a minimum (inclusive) and maximum (exclusive).
1 The only interesting thing in DebugMe.ps1 was that there’s a possible extra bug because the script uses the variable $x without initializing it or taking it as a parameter — $x is a really popular variable ;-P and not initializing it could result in really strange results from this script. I fixed it (within the scope of the rules: only modify existing lines) by explicitly stating the script scope:
foreach($i in Get-ChildItem C:\Scripts -recurse)
{
if ( ($i.CreationTime -lt ((Get-Date).AddDays(-10))) -and ($i.Extension -eq ".txt") )
{
Copy-Item $i.FullName C:\old -whatif
$i.Name
$script:x = $script:x + 1
}
}
""
"Total Files: " + $script:x