If only I were

Building Great Software

PowerShell File Search

with 4 comments

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 ?.

Advertisements

Written by Chris Sutton

April 1, 2008 at 7:49 pm

Posted in Technology

Tagged with , ,

4 Responses

Subscribe to comments with RSS.

  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.

    EBGreen

    April 2, 2008 at 2:39 pm

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

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

    EBGreen

    April 2, 2008 at 2:46 pm

  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.

    Chris Sutton

    April 3, 2008 at 4:37 pm

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


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: