Searching through Files with PowerShell

Windows PowerShell is the new command line shell and language that will be released soon. I’ve been poking around with PowerShell and the more I see of it the better I like it. I rarely use the old cmd.exe shell for test automation tasks because it just doesn’t have the horsepower to do much. A good example is searching through the file system for a text string. Here’s a tiny PowerShell script that searches the current directory and all sub-directories for .txt files which contain the string "orange":
# findtext.ps1
$target = "orange"
$files = get-childitem -recurse -include *.txt
$matches = $files | select-string $target
$results = $matches | group -property filename
write-output $results
# end script
The ‘#’ symbol is a comment line. Variables, such as $target, are preceded with a ‘$’ character. The "get-childitem" is a cmdlet which fetches an object — this is a key concept to PowerShell and the source of much of its power. The statement retrieves a set of all .txt files from the current directory and all sub-directories, and stores that set into $files. Next I use the select-string cmdlet to grab information about the set of all files which contain the target ("orange"). Then I group that information by filename into object $results. Finally I use the write-output cmdlet to display the results, which might look like:
Count Name                      Group
—– —-                      —–
    2 Colors.txt                {Colors.txt, Colors.txt}
    1 Fruits.txt                {Fruits.txt}
This shows the script found a total of three occurrences of "orange". The target was found in two different but identically named Colors.txt files, and also in a "Fruits.txt" file. Pretty cool. I can easily parameterize my script by replacing the first statement with:
$target = $args[0]
Then I can run my script like:
PS C:\Data\Alpha> C:\Data\Alpha\findtext.ps1 orange
This will run my findtext.ps1 script, and search for "orange" in all .txt files in directory Alpha and all of Alpha’s sub-directories.
This entry was posted in Software Test Automation. Bookmark the permalink.