Click here to monitor SSC
Av rating:
Total votes: 20
Total comments: 3


Michael Sorens
Harnessing PowerShell's String Comparison and List-Filtering Features
07 June 2011

"Hmm. Wifi Hotspot!"

When you are first learning PowerShell, it often seems to be an 'Alice through the looking-glass' world. Just the simple process of comparing and selecting strings can seem strangely obtuse. Michael turns the looking-glass into wonderland with his wall-chart of the PowerShell string-comparison operators and syntax.

PowerShell is an outstanding successor to the Windows/DOS batch language. It provides a powerful and flexible framework for creating intricate scripts to automate your administrative or repetitive tasks.

The tradeoff for this added power and flexibility, though, is an increased complexity:  learning PowerShell is not a trivial undertaking. Delving into a completely new language is very much like embarking on Alice's adventure down the rabbit-hole: you are constantly reaching unexpected impasses and taking off on  tangents, but all efforts, large and small, eventually culminate in reaching the goal—in this case, executing the most elementary of programs.

Please imagine what it is like for anyone falling into this particular rabbit hole. 


"Funny, the doors are getting
smaller, but the size of
Windows keeps growing."

It was all very well to say "Program with me," but the wise little Alice was not going to do that in a hurry. "No, I'll try a few simple things first," she said, "and see whether it's poisonous or not"; for she had read several little stories about programmers who had got burnt, and eaten up by ridiculously obtuse languages, and other unpleasant things, all because they would not remember the simple rules their friends had taught them, ‘see if it is right for you’:

“Let’s try listing all the files in the current directory. Well, just type... hmm, how do you do that in PowerShell? Well, in batch that is just dir... hey, that works! Good heavens, even the Unix ls command works.”

 Both of those sound like convenient aliases, Alice surmised. “Well, aliases to what? Let's check the help system. Hmm, how do you access help? ... Aha! The get-help cmdlet. The alias help can be accessed with get-help about_aliases.”  From there Alice found that …
      Get-Alias -name dir
… reveals the underlying cmdlet, Get-ChildItem. “Great. Now how to exclude binaries, i.e. .dll or .exe? Check the parameters to Get-ChildItem in the help system.” She then stumbled over the fact that you could even ask for help on the dir alias to get the same details... but Alice felt she was digressing.

“So now”, she mused, “I know that …

      Get-ChildItem -exclude *.dll,*.exe
 … will answer the original question. Now, let's add another constraint: do not output anything unless there is a file named ‘Process_Me’ in the directory. Clearly a simple conditional should suffice. In many languages, that would be an if statement. In PowerShell, what is a statement? Is that a cmdlet? Or perhaps a command?”

I started out in Accountancy,
but then discovered Lisp

After experimenting with the help system for a while, she realized that cmdlets tend to have the form verb-noun (e.g. Get-ChildItem) while language constructs (if, switch, etc.) are commands. Command help is accessed via get-help about_command. So checking about_if, shows it is a fairly standard if/else. There is also an elseif for multiple conditions. The test condition itself must be in parentheses. But what of the form of the test condition itself? Should it be ...
  ($name = "Process_Me")

... or ...
  ($name == "Process_Me")
...or ...
  ($name === "Process_Me")?

Alice was surprised to find that it was none of these. The help page shows just two trivial examples:
-gt for greater than and -eq for equals. Curious, she thought, but OK, what about the rest? No information on that page. It does, at least, give a hint to read up on about_Comparison_Operators to learn more. On that page she found some further details and some further references... quite a lot of material to digest—though not terribly taxing—before she could write a simple conditional!


Particularly intriguing to me is PowerShell's core fundamentals of string handling with respect to conditionals. Though the PowerShell help system is better than some, following the above approach will still not get you a complete picture of understanding string comparisons, when you consider exact vs. wildcard vs. regex matches, negations, substrings… and that is just for scalar strings. PowerShell also provides arrays, and you can pass arrays through pipelines and filters, etc. The accompanying wallchart conglomerates every bit of this information about strings into a single page reference that should make using this core area of PowerShell quick and easy.

The full PDF wallchart can be downloaded from the speech-bubble at the head of the article. You can view the wallchart in a browser, as HTML, by clicking the image of it



This article has been viewed 11885 times.
Michael Sorens

Author profile: Michael Sorens

Michael Sorens is passionate about software that makes you more productive. To that end, he has developed open source libraries in several languages (see his API bookshelf) as well as a unique database comparison tool (with a 150+ page manual), SqlDiffFramework, letting you compare data from heterogeneous systems (SQL Server, Oracle, MySql, plus any ODBC data source). He is a software engineer with BS and MS degrees in computer science/engineering who has worked at Fortune 500 firms and at startups. Current passions include PowerShell, .NET, SQL, and XML technologies (see his full brand page). Spreading the seeds of good design wherever possible, he enjoys sharing knowledge via writing (see his full list of articles), open-source web sites (cleancode.sourceforge.net and SqlDiffFramework.codeplex.com), and teaching.

Search for other articles by Michael Sorens

Rate this article:   Avg rating: from a total of 20 votes.


Poor

OK

Good

Great

Must read
 
Have Your Say
Do you have an opinion on this article? Then add your comment below:
You must be logged in to post to this forum

Click here to log in.


Subject: Awesome
Posted by: Julie Smith (not signed in)
Posted on: Thursday, June 23, 2011 at 8:07 AM
Message: I LOVE THIS!!! Brilliant adaptation of creepy non-copywrighted children's literature to geekspeak.

Subject: Write a book
Posted by: Jimmy Jen (not signed in)
Posted on: Thursday, June 23, 2011 at 9:58 AM
Message: Have you consider to write a book about Powershell ?
The attached Powershell string comparison PDF file is real handy. Thanks for putting it together.

Subject: Agreed... Awesome
Posted by: --Jeff Moden (not signed in)
Posted on: Thursday, June 23, 2011 at 1:06 PM
Message: Outstanding. The story is fun but the real key is the relations to familiar things and the simplicity of the explanation. The wall chart is definetly the bees knees.

I'd love to see a similar article on file handling with PowerShell.

 






recommended site pinvoke

PInvoke.net is a user-driven wiki which provides .NET developers with native method signatures, so they don't have to spend time writing them from scratch.




Top rated articles
C# Async: What is it, and how does it work?
 The biggest new feature in C#5 is Async, and its associated Await (contextual) keyword. Anybody who is... Read more...

Towards the Perfect Build
 An automated build and deployment system is no longer a dream. Now that PowerShell has matured as a... Read more...

Practical PowerShell: Pruning File Trees and Extending Cmdlets
 One of the most radical features of PowerShell is amongst the least known. It is possible to extend... Read more...

TortoiseSVN and Subversion Cookbook Part 4: Sharing Common Code
 Michael Sorens continues his series on source control with Subversion and TortoiseSVN by describing... Read more...

Feature Usage Reporting in Early Access Programs
 After doing Web development, you can get very used to the luxury of having basic information about your... Read more...

Most viewed articles
A Complete URL Rewriting Solution for ASP.NET 2.0
 Ever wondered whether it's possible to create neater URLS, free of bulky Query String parameters?... Read more...

Visual Studio Setup - projects and custom actions
 This article describes the kinds of custom actions that can be used in your Visual Studio setup project. Read more...

.NET Application Architecture: the Data Access Layer
 Find out how to design a robust data access layer for your .NET applications. Read more...

Web Parts in ASP.NET 2.0
 Most Web Parts implementations allow users to create a single portal page where they can personalize... Read more...

Calling Cross Domain Web Services in AJAX
 The latest craze for mashups involves making cross-domain calls to Web Services from APIs made publicly... Read more...

Over 400,000 Microsoft professionals subscribe to the Simple-Talk technical journal. Join today, it's fast, simple, free and secure.

Join Simple Talk