If only I were

April 1, 2008

PowerShell File Search

Filed under: Technology — Tags: , , — Chris Sutton @ 7:49 pm

If you are looking for a file or directory in your file system try something simple like this:

dir -recurse -filter *power* | sort name | ft directory, name

dir is an alias to the Get-ChildItem cmdlet – it does pretty much what it did in the DOS world (and more). The -recurse parameter looks in subdirectories as you might expect. -filter lets you pass in a file or directory name or pattern. sort name … well you can figure this out.  ft directory, name is an alias to the Format-Table cmdlet and it lets you decide what columns you want in the table that gets outputted.

Here is a slightly more powerful expression:

dir -recurse | ?{$_.name -match “^*.jpg|gif$”} | sort name | ft directory, name

With this expression you can do comparisons on specific fields. Here I’m doing a regex pattern match for all files that end with jpg or gif. ? is an alias to the Where-Object cmdlet. where is also an alias to Where-Object and might be more readable than ?.

4 Comments »

  1. For the last example, the Where-Object clause is not really required since the -include parameter takes an array:

    dir -recurse -include (‘*.jpg’, ‘*.gif’) | sort name | ft directory, name

    Although it is still a good example that you can use the Where-Object clause for more complex result filtering.

    Comment by EBGreen — April 2, 2008 @ 2:39 pm | Reply

  2. Ooops…got a stray grave character in there somehow. It should be:

    dir -recurse -include (‘*.jpg’, ‘*.gif’) | sort name | ft directory, name

    Comment by EBGreen — April 2, 2008 @ 2:46 pm | Reply

  3. @EBGreen, thanks. I hadn’t played with -include yet, but that is cool to see that it lets you do pattern matching. It’s definitely the simpler route.

    Comment by Chris Sutton — April 3, 2008 @ 4:37 pm | Reply

  4. [...] Chris Sutton shows us how to do a PowerShell File Search. [...]

    Pingback by Weekly Link Post 36 « Rhonda Tipton’s WebLog — April 6, 2008 @ 3:30 pm | Reply


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.