In my ongoing chronicle of solutions to the 2008 scripting games events … the task in beginner’s event 3 was to copy the first line of each text file in a folder into a new text file. This task is so trivial in PowerShell that my solution is the same as the Scripting Guy’s:


get-content C:\Scripts\*.txt -total 1 | set-content C:\Temp\Newfile.txt

If you need that explained … well, you’re just going to have to read their explanation, because quite frankly, it’s too boring to get into.

Beginners Event 4

For beginner’s event 4 the task was to read in the content of the script file itself and count the characters. This is actually just as easy as the last one, but somehow, the scripting guys’ solution went off into vbscript loop land again. They actually loop through each line and manually add up the line length. My script is 55 characters long ;-) and looks like this:


gc $MyInvocation.MyCommand.Path|Measure-Object -C|fw C*

Slick, right? Ok, I’ll explain that one. $MyInvocation is a built-in variable which contains everything there is to know about what’s running and how it was started. $MyInvocation.MyCommand contains the information about the command that’s running, it’s .Path if it’s a script, and so on. On the other hand, $MyInvocation.InvocationName contains the first thing on the command-line, and so even though the scripting guys used it, you should never assume InvocationName will contain the script path — it would fail if the script had been run by dot-sourcing, or by invoke-expression or by the invoke character & or … well, you get the idea, it would fail often.

Anyway, once you have the path of the script you get-content (gc is one of the built-in aliases for that) and pipe it into the Measure-Object cmdlet which has a -Characters parameter. As always, when passing parameters, you only need to pass enough to differentiate the parameter from others.

In normal use, that would be enough: the output of Measure-Object is simple and very clear. For the scripting games, we want to be a little more precises, so we pipe the output to the Format-Wide cmdlet using it’s built in alias “fw” — unlike Format-Wide and Format-List, Format-Wide won’t add headers, so it outputs just the number. However, we have to specify which property to show, but since there’s only a few, we can use a wildcard match to select the Characters and a single letter is enough to differentiate from the other properties: Lines, Words, and Property. And that’s it!

Comments are closed.