# Wednesday, March 05, 2008
« iTunes messages not getting any better d... | Main | Three Simple Rules for (my) Tech Bloggin... »

One of the things I miss from my Unix/Linux days is Grep.  Previously I have tried things like Cygwin, but was never quite satisfied.  I am quite excited about PowerShell and am always trying to get more PS> in my life :-)

I'm using Powershell almost daily to replace Grep.

To start, this is all based on the Get-ChildItem cmdlet.  The best way to think about Get-ChildItem is it does what the Dir command did in DOS.  One important difference is it is not just for files, and can be used to return all items in a location - and it is up to each provider to decide what a location & item means to it!

For the PowerShell n00bie, you can just use cd around the filesystem and when you type dir, you are really running Get-ChildItem.  In fact when you type cd you are really running Set-Location.  For a full list of aliases for common commands, run Get-Alias.

To search in file names:

The following command searches for .aspx & .ascx files in the current directory that have the word "metro" in the filename.

PS > Get-ChildItem -Include *metro*.as?x

To search inside text files:

The following command searches inside .aspx & .ascx files in every subdirectory that have the word "metro" in the filename, and has the word "train" inside the file.

PS > Get-ChildItem -Recurse -Include *metro*.as?x | Select-String -Pattern train

You are also able to add the -CaseSensitive parameter to the end of the Select-String command, by default it will search case insensitive.

NB:  I have used the full names of the parameters of the commands.  This may look clunky, but:

  1. I wanted the examples to be clear, because this is a blog :-)
  2. The Tab-Completion feature works for parameter names so they are not hard to type
  3. You can use the smallest number of letters that identify a parameter.  For example, if a cmdlet accepts a -Recurse and a -Record param, you would only need to use -Recu and -Reco respectively.

Update: A lot of parameters accept an array as input.  The syntax for listing these is as a comma seperated list.

An example where this applies to our example is searching through multiple file types, i.e. .aspx and .cs.

The following example searches both .aspx/.ascx files and .cs files with the word "metro" in the filename.

PS > Get-ChildItem -Recurse -Include *metro*.as?x,*metro*.cs

Listening To:  Wicket Beat Sound System, Inner Styles

Wednesday, March 05, 2008 11:25:19 PM (AUS Eastern Daylight Time, UTC+11:00)  #    Disclaimer  |  Comments [0]  |