2008 Winter Scripting Games

Solution to Beginner Windows PowerShell Event 4: Count Yourself In

Event 4 Solution


Windows PowerShell solution to Event 4 in the 2008 Winter Scripting Games.

Solutions are also available for VBScript and Perl.

*

Event 4 – Count Yourself In

To correctly solve this event you needed to be able to determine the name of the running script and read from that script file. Here’s one possible solution:

$script = $MyInvocation.InvocationName
$lines = Get-Content $script
foreach ($line in $lines)
    {$a += $line.length}
$a

The very first line of this script is probably the key to whole thing:

$script = $MyInvocation.InvocationName

If you got this line you were well on your way to solving this event. (And if you read the Scripting Games Tips you got this line.) All we’re doing here is using the Windows PowerShell reserved variable $MyInvocation and retrieving the InvocationName property. This property contains the full path and filename to the running script – this script, as a matter of fact. We place that name in the variable $script.

Now we want to read the entire contents of this file. That’s really easy in PowerShell. We simply call the Get-Content cmdlet:

$lines = Get-Content $script

Get-Content returns the entire contents of the file we pass in as a parameter, in this case the name of the script that we stored in the $script variable. Get-Content returns the contents of the file as an array, each line of the file being an element in the array. We assigned this output to the array $lines.

As we said, each line of the file is now stored as an element in the $lines array. So to count all the characters we set up a foreach loop to loop through the array and count the characters in each line, like this:

foreach ($line in $lines)
    {$a += $line.length}

Each time through the foreach loop we add the contents of the length property of the string to the variable $a. If you’re wondering how that’s happening, += is PowerShell shorthand for “add to itself.” In other words this line:

$a = $a + 1

is equivalent to this line:

$a += 1

We’re simply saying “add this value to $a then assign the result back to $a.”

You don’t get any points in this event for simply counting the characters though – you actually have to display the result:

$a

That wasn’t so hard, was it? Oh, and in case you’re wondering, unlike with VBScript, we don’t need to worry about carriage-return linefeed characters in PowerShell. The Get-Content cmdlet automatically strips them off for us. That’s certainly nice, isn’t it?


Top of pageTop of page