2008 Winter Scripting Games

Solution to Beginner Windows PowerShell Event 3: Let’s Get Together

Event 3 Solution


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

Solutions are also available for VBScript and Perl.

*

Event 3 – Let’s Get Together

This event was all about finding files within folders, reading from those files, and even creating new files. Whew, that sounds like a lot. But in Windows PowerShell it couldn’t be simpler. Take a look:

Get-Content C:\Scripts\*.txt -totalcount 1 | Set-Content C:\Temp\newtext.txt

Yes, that’s it. Really. It takes only one line of PowerShell to do all that. We don’t really even need to go through this it’s so simple.

What’s that? Oh…well, okay, we’ll go ahead and explain this nice little script.

The script has two parts, separated by a pipeline (|). The first part uses the Get-Content cmdlet to read in all the text files in the C:\Scripts folder. How does it do this? Well, we pass Get-Content two parameters. The first is the path to the file we want to read. Notice our filename has an asterisk character in it, *.txt. The asterisk is a wildcard, meaning “anything.” So the path we’re passing in is for any file in the C:\Scripts folder that ends with a .txt extension.

The second parameter we pass to Get-Content is the –totalcount parameter. Remember, we want to read in only the first line of each text file. We do this by assigning 1 to the –totalcount parameter, meaning return only line 1 from the file. The result of this call to Get-Content is an object that contains each line from each text file in C:\Scripts.

Now that we have all those lines, we need to write them to a new file. So we pass the whole list over to the Set-Content cmdlet. That’s what the pipeline does: it takes the results of the first part of the command (in this case, the call to Get-Content) and passes them to the next part of the command (the call the Set-Content).

We’ve passed only one parameter to Set-Content: the name of the text file we want to write to (C:\Temp\newtext.txt). If this file doesn’t exist, Set-Content will create it for us. So Set-Content takes all the lines that were read by Get-Content and write them to C:\Temp\newtext.txt.

We’re done. Yep, that’s it, end of event. With Windows PowerShell, this event wasn’t difficult at all, was it?


Top of pageTop of page