Question

File extension search

Asked by: Yeniye

Hi there,

I just wanted to have a file search on my machine and external device with only the extension like  ".xyz".I know i can easily search using dir on each drives but it is not efficient .I just needed an efficient powershell script for a file search with the file extension.
please it is urgent.

Thanks.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-09-06 at 23:52:35ID24711971
Tags

powershell

,

search file

Topics

Powershell

,

Algorithms

,

Scripting Languages

Participating Experts
4
Points
500
Comments
24

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. search dir
    hi can someone give an example of how to search a dir for particular files, eg *.pcx , then return the found file names to a combo box , without the extention thankyo mit
  2. Dir versus FSO
    Hi Everyone, In regards to using the Dir command and using FileSystemObject, I'm curious as to what people think is better. I used to use dir for everything, until about a year ago when someone pointed out to me (I can't find the thread) that FSO is more efficient. I've be...
  3. Very Urgent -- Efficient Multi threaded File Search using T…
    I have return a File search program which i thought was most efficient but yet i wasn't because i was creating very high number of threads which degraded the performance hence i Decided to convert this program to Thread Pool based one so that the number of threads created wi...
  4. Mod Rewrite: .xyz to 404
    I want to rewrite all pages with a .xyz extention to /404/index.htm So: http://www.example.com/sub/dir/page.xyz Should be redirected to: http://www.example.com/404/index.htm
  5. Recursing through Remote registry  in powershell
    Hi, I am trying to recurse through a remote registry key path and search through it for a value name and get the value data .Hence i need to give it atleast a subkey to start from so as to avoid searching time delay through many nodes. $regpath = "HKLM:\System\CurrentCon...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: t0t0Posted on 2009-09-07 at 00:13:04ID: 25273189

You say:

    "i can easily search using dir on each drives but it is not efficient"

Firstly, you say you can "easily" search using DIR - obviously, that's what DIR was designed for!

Then you say, "it is not efficient" - what do you mean 'it is not efficient'? In what way?

DIR is the proper tool for what you have described above. To search for all files with just the extension ".XYZ" enter the following DIR command:

  DIR *.xyz

It's as easy as that. And then your DOS will display all your files with an '.xyz. extension.

So, how much more efficient do you want DIR to be?

To get a list of all options supported by DIR, enter the following command:

  DIR /?

 

by: mplungjanPosted on 2009-09-07 at 01:07:44ID: 25273426

@t0t0 "and external devices"

http://www.microsoft.com/technet/scriptcenter/topics/winpsh/manual/default.mspx

http://www.microsoft.com/downloads/details.aspx?familyid=df8ed469-9007-401c-85e7-46649a32d0e0&displaylang=en&tm

http://technet.microsoft.com/en-us/scriptcenter/dd742419.aspx

http://www.johndcook.com/PowerShellCookbook.html

I had a quick look, but I do not have powershell on my machine

Perhaps this is a start - I have never written powershell before

diskpart < listv.txt > vols.txt
echo "" > output.txt
# we need to skip the header somehow and stop at the end of the list
# drive names are one letter so perhaps look at the length of the 3rd word
foreach($line in (get-content vols.txt)) {
  $vol = $line.split()[2]
  $cmd = "dir $vol:\*.$args[0] /s >> output.txt"
  invoke-expression $cmd
}
 
 
 
where listv.txt contains
list volume
exit

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:

Select allOpen in new window

 

by: t0t0Posted on 2009-09-07 at 01:20:12ID: 25273470

Dear Yeniye

I understand your frustration with the DIR command. I must admit it's not the friendliest of commands DOS has to offer and at times, the squiggly-like characters following the command can be so cryptic at first.

Unfortunately, DIR with it's often cryptic bits and pieces that follow it is what we're normally stuck with. Oh, why-oh-why couldn't the makers or DOS allow us to enter commands like this:

    LIST ALL FILES WITH AN XYZ EXTENSION NAME

Surely, that can't be rocket-science!

So we're stuck with having to get by with DIR. Here are a few example uses of DIR that I picked up fairly quickly. It might help to jot a few of these down on the inside of your cigarette packet or even on your forearm....

   DIR *.*                 <-- The '*' (star) (SHIFT-8) means 'ANY'. In this case, 'any' filename with 'any' extension.
                                       In other words, EVERY file.

   DIR *.TXT            <-- Any filename with a TXT extension.

   DIR LETTER.*    <-- Any file named LETTER (with any extension).

   DIR LETTER*.*   <-- Any file whose name STARTS with 'LETTER'

All the above commands work in the current folder only, but you can extend these searches to other folders.

   DIR C:\*.XYZ              <-- All files with an XYZ entension in the root folder of drive C:

   DIR C\:temp\*.XYZ    <-- All files with an XYZ extension in the folder C:\temp\

   DIR /S C:\*.XYZ          <-- All files with an XYZ extension STARTING in root folder of drive C:....
                                              and all sub-folders extending from the root folder of drive C:

                                              In other words - the WHOLE of drive C:

Hmmm.... I can understand now why we don't use plain English... Wow, imagine having to type that in every time we want to search the drive.

Finally, your system may support the following:

   DIR /S C;\*.XYZ  D:\*.XYZ

This will search your whole drives - both C: and D:. Wow... I'm not even going to try putting that into words!!

I hope some of that helps you get by for the moment but please remember, it gets easier the more you use it. And of course, when you're ready to know more, just enter the following command:

   DIR /?

which will display DIR's help pages giving many more options.

But take note, you don't need to know it all at once - so take your time and learn just waht you need to get by for now.

Good luck.

 

by: t0t0Posted on 2009-09-07 at 01:47:20ID: 25273561

Oh, by the way, the output from DIR can be saved to a file. The advantage of this is that you can then open the file and browse through the list of filenames. Here's how it's done:


     DIR /S c:\*.xyz d:\*.xyz >list.txt

The '>list.txt' at the end of the command tells DIR to output it's results to a file named LIST.TXT instead of diaplaying it's output on the screen.

 

by: activephotoPosted on 2009-09-07 at 05:42:41ID: 25274639

Hi,
Here is a Powershell script that you can use that scans your computer for drives (note network shares) and saves the filename and path into a file (and shows them on the console).

Its easy to modify this script if you want to do other things with each file. Each file is saved as a FileInfo object into $files, so you can get size, dates etc as well.

Change the variable at the top named $filter to search for different file extensions like "*.txt" or anything else

Good luck!

/ Mikael

$Files = @()
$Filter = "*.xyz"
#Excludes network connected shares
Get-WmiObject win32_logicaldisk | where {$_.drivetype -ne 4} | 
    ForEach-Object { 
        Write-Host "Scanning : " $_.deviceID -foregroundcolor blue
        if (Test-Path -Path $_.DeviceID) {
            Get-ChildItem -Filter $Filter -Path $_.DeviceID -Recurse | 
                ForEach-Object {
                    #Write each file it finds and adds to collection
                    $Files += $_
                    $_.FullName
                }
        }
    }
    #export to CSV file
    $files | select FullName | Export-Csv -Path "files.csv" -NoTypeInformation
    Write-Host "Found totally " $files.count " files"
    $Files = $null
    $filter = $null    
    
    

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:

Select allOpen in new window

 

by: Chris-DentPosted on 2009-09-07 at 05:51:22ID: 25274683


I can simplify the script above a bit :)

Note that no matter what we do here we're not altering the underlying algorithm, efficiency is not impacted (depending on how you define that). Also note that "dir" in PowerShell is an alias for Get-ChildItem, so by using Get-ChildItem you are using "dir".

Chris

$Filter = "*.xyz"
Get-WMIObject Win32_LogicalDisk -Filter "DriveType='3'" | %{
  Get-ChildItem -Filter $Filter -Path $_.DeviceID -Recurse | Select-Object FullName
} | Export-CSV "files.csv" -NoTypeInformation

                                              
1:
2:
3:
4:

Select allOpen in new window

 

by: mplungjanPosted on 2009-09-07 at 05:59:12ID: 25274734

Now for truly usefulness, make it look INSIDE each file for string :)

 

by: Chris-DentPosted on 2009-09-07 at 06:01:17ID: 25274753


Select-String would do that if you were feeling inclined :)

Chris

 

by: activephotoPosted on 2009-09-07 at 06:15:28ID: 25274847

if using my script above you can put in one of the following codelines into foreach-object clause (line 9-13), depending on what you want to do with it.

those are of course only examples of how to get information, use Get-Help Select-String to get more info about how to use it (or ask again

/ Mikael

#Gets the line number in the file where the string is
Select-String -Pattern "string to search for" -path $_.fullname | select {$_.lineNumber} 
 
#Gets the filename where the string are found
Select-String -Pattern "string to search for" -path $_.fullname | select {$_.FileName}
 
 
#Gets the actual line in the file where the string is found
Select-String -Pattern "string to search for" -path $_.fullname | select {$_.line}   

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:

Select allOpen in new window

 

by: mplungjanPosted on 2009-09-07 at 06:19:28ID: 25274864

Can I be a bother and ask for

$string found in file $filename on line $line
?

Thanks

 

by: Chris-DentPosted on 2009-09-07 at 06:26:00ID: 25274902


Select-Object will do that, although it would take a bit more to make it a sentence. Might want to substitute FileName for Path here, more appropriate for searches.

...
Select-String -Pattern "string to search for" -path $_.fullname | Select-Object FileName, Pattern, LineNumber
...

Drifting away from the original question though...

Chris

 

by: mplungjanPosted on 2009-09-07 at 06:31:53ID: 25274939

Not sure we are :)

 

by: YeniyePosted on 2009-09-07 at 09:50:13ID: 25276176

Chris-Dent and activephoto:

Thank you for the code .That helps.But  the file with the extension .xyz is not expected to be in some folders so i need to exclude this folders like windir, programfiles ,appdata. etc. to increase the the speed of search.
thanks

 

by: YeniyePosted on 2009-09-07 at 09:52:46ID: 25276184

By the way
which one is more fast  the .Net namaespaces  or WMI if we have the previlage of using one of them
in our code.

 

by: Chris-DentPosted on 2009-09-07 at 11:56:40ID: 25276732


.NET if you ask me, WMI is much heavier in my experience. PowerShell uses .NET with only a minor overhead for the Shell. Notice that Get-Item and Get-ChildItem give you System.IO.FileInfo and System.IO.DirectoryInfo objects.

To improve beyond that you'd have to look at the APIs but that's going to be C++ or equivalent.

Excluding folders is fine, except we'd have to write our own recursion. You have to love that the "Exclude" parameter carries a note:

"This parameter does not work properly in this cmdlet."

Fun :)

Anyway, potential implementation of that below. The Pattern parameter and Exclude parameter are Regular Expressions which makes it rather complex, but I quite like it :)

Exclude is optional, you can just leave it off, the other two have default values.

Chris

Function Get-File {
  Param(
    [String]$Path = "C:",
    [String]$Pattern = "",
    [String]$Exclude
  )
 
  # Set $DebugPreference to "Continue" to see this, default is SilentlyContinue
  Write-Debug "Searching: $Path"
 
  If ($Path -NotMatch $Exclude -Or $Exclude -eq $Null -Or $Exclude -eq "")
  {
    # Get the children for this level
    $Children = Get-ChildItem $Path
    # Drop down through folders
    $Children | ?{ $_.PsIsContainer -eq $True } | %{ 
      Get-File -Path $_.FullName -Pattern $Pattern -Exclude $Exclude
    }
    # Return objects which match the pattern
    Return $Children | ?{ $_.Name -Match $Pattern }
  }
  Else
  {
    Write-Debug "Skipping: $Path"
  }
}
 
# Make some exclusions as a regular expression
$Exclude = "$($Env:ProgramFiles -Replace '\\', '\\')|$($Env:AppData -Replace '\\', '\\')|" + `
  "$($Env:WinDir -Replace '\\', '\\')"
 
# Pass in the starting point (might interate use the WMI loop to get this one)
Get-File -Path "C:" -Pattern ".*\.xyz" -Exclude $Exclude | Select-Object Name, FullName, Length

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:

Select allOpen in new window

 

by: YeniyePosted on 2009-09-09 at 23:20:03ID: 31625608

Thank you very much!!!

 

by: t0t0Posted on 2009-09-10 at 12:56:13ID: 25303642

Vee Mod. I read your suggested 'alternative' version of my reply.... You have a natural way with words.... I've taken your comments on-board should there be a similar occurance.
   

 

by: t0t0Posted on 2009-09-10 at 13:05:35ID: 25303722

Thank you for the comment regarding my explanation of the DIR command. Funnily enough, I re-read it (since receiving your comment) and I must admit (with a bit of spit and polish) it does sound quite beginner-friendly.... something I suppose we more experienced DOS user forget how to relate.

Thank you anyway.

By the way, I'm not used to being treated nicely by moderators so this is a first.
 

 

by: t0t0Posted on 2009-09-10 at 13:06:36ID: 25303737

PS. I posted these in the wrong place, haven't I?......

 

by: Chris-DentPosted on 2009-09-10 at 13:21:16ID: 25303878


Yes, but don't worry too much about it :)

Chris

 

by: YeniyePosted on 2009-09-17 at 10:00:18ID: 25358400

Hi Chris-Dent

I was using your function and i was trying to restrict the from searching  C:\FOO\Bar
but i want it to search in C:\FOO.But still i should be able to search C:\Users\userA\Desktop or Documents.
I don't want to go more than two stages in any arbitrary folders

 

by: YeniyePosted on 2009-09-17 at 12:05:53ID: 25359732

Actually i got thanks

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...