2009-06-10

Powershell Scripting Games - Day 1

If you have not heard about it yet - the Summer Scripting Games 2009 have started.

Well I am one day late (sorry!!) but I was trying to figure out the solution for the Event for Day 1 -Beginner - it was late last night and my brain was not working too well.

So I looked online today and want to thank Hugo Peters for helping me out with his solution for this event.

The problems I had with this solution was the fact that the file was not formatted correctly - there were spaces and tabs, therefore I had to parse the file and replace the spaces with tabs(Line 7).
Also how to extract the information and to place it into an array (Lines 13 - 24).

Here you go.

   1: # Read the input file
   2: $InputFile = ".\100 Meter Event.txt"
   3: $Content = Get-Content $InputFile
   4:  
   5: #Since the lines are not all separated with tabs and some are with spaces,
   6: #we will replace all spaces in the file with tabs
   7: $Content = $Content | foreach-object { $_ -replace "(.*)\s(.*)","`$1`t`$2" } 
   8:  
   9: # Prepare output collection
  10: $myCollection = @()
  11:  
  12: # Loop through lines in the file, exept the first one
  13: ForEach ($Line in ($Content[1..$($Content.Length)]))
  14:     {
  15:     # Properties are separated by tabs
  16:     $myObj = "" | Select Name, Country, Time #Create a new object with the columns
  17:     #Splitting the line on the tab returns 3 values - we get each one in turn and 
  18:     #add it to the appropriate column
  19:     $myObj.Name = $Line.Split("`t")[0] #Retrieve the Name
  20:     $myObj.Country = $Line.Split("`t")[1] #Retrieve the Country
  21:     $myObj.Time = $Line.Split("`t")[2] #Retrieve the time
  22:     # Add to output
  23:     $myCollection += $myObj
  24:     }
  25: # Now we sort the the object on the Time column and Select the top 3 results
  26: $myCollection | Sort Time | Select -First 3