Posts Tagged ‘Calendar’

This continues my series of solution posts for the 2008 Scripting Games with my solution for the Advanced Event 4 which was about drawing a “graphical” calendar in the console. Basically, this is a simple task, and the only complication was the requirement to allow passing in the month.

There are solutions from the Scripting Guys and Ed Wilson already available, and both of them are pretty good solutions, so I would have left this post in the draft bin if it wasn’t for the fact that I already showed off screenshots of my final script (which is a bit over the top). Because I wrote such a complicated script in the end, I wanted to show you how it started before I show you how it ended up:


param([DateTime]$now = (Read-Host "Please enter a date"))
# make sure that $now is the first day of the month:
$now = $now.AddDays(1-$now.Day)

# Write the month string at the top
$now.ToString("   MMMM, yyyy   ")

# Write the day names below it
" Su Mo Tu We Th Fr Sa "

# Figure out the day of the week for the first day of the month
# Note: if you don't cast to [int], this returns the name, like "Monday"
$dow = [int]$now.DayOfWeek

# Total number of days ...
$days = [DateTime]::DaysInMonth($now.Year, $now.Month)

# write the calendar as a single string by joining an array of strings ...
# Starting on Sunday before the first day of the month (aka: 1-$dow)
# Ending after the number of days in the month ...
Write-Host "" @(switch((1-$dow)..$days){
  {$_ -lt 1} {"  "}                # -lt 1, just insert padding  
  {$_ -gt 0} {"{0,2}" -f $_}       # -gt 0, the number, padded to 2 chars
  {0 -eq (($_+$dow) % 7)}{"`n"}})  # 7 Mod 7, insert a new-line

See that? Not really very complicated, right? It’s just about ten lines of code, and three of them are unnecessary variable assignments which just help make the script more readable (actually, there’s really only 2 necessary lines1). There’s a couple of tricks here though: Read the rest of this entry »

I’ve labeled this part 1 because I’m planning on writing more about a couple of my solutions to the Microsoft Scripting Games 2008, a few of my solutions are good examples of the power of PowerShell or of scripting languages in .Net, or just neat features.

Just for fun, I thought I’d post a screenshot of my solution for Event4 because I saw that /\/\o\/\/ was...

Search My Content