user1773475
user1773475

Reputation: 43

Search and sort directory and subdirectory using Batch Script

I have been trying to do a search of the user directory and subdirectories in a primary school for all applications, music, videos and archived files to check what the kids are hiding from me. I have been using a basic dir script similar to this:

dir C:\Sample\*.exe, C:\Sample\*.rar, C:\Sample\*.mp3  /s /b /OE > D:\Result.txt

This provides me with an output of ALL files of those types sorted by user name.

What I want to know is, is there an easy way to either change the search to sort by type or to use the sort command afterwards to sort by the last character/s of the file.

Sample of output:

U:\adwan4\My Documents\My Videos\PhotoStory1.wmv
U:\ageeg2\My Documents\install_flashplayer11x32ax_gtbp_chra_aih.exe
U:\amcka55\My Documents\My Music\Angus.wmv

I have come up with something that appears to do the trick using Find along the lines of:

Find ".exe" D:\Result.txt >>D:\Sorted.txt

This appears to work fine for the avi, exe, etc. However I would be very happy for any suggestions.

Upvotes: 3

Views: 1419

Answers (3)

user1773475
user1773475

Reputation: 43

For anyone interested, my initial solution (which took a lot more typing because it has no loops) looks something like this:

ECHO Off
dir U:\*.exe, U:\*.rar, U:\*.mp3  /s /b > D:\Result.txt
Echo Applications > D:\Sorted.txt
Echo --------------------------- >>D:\Sorted.txt
Find ".exe" D:\Result.txt >>D:\Sorted.txt
Echo Music >> D:\Sorted.txt
Echo --------------------------- >>D:\Sorted.txt
Find ".mp3" D:\Result.txt >>D:\Sorted.txt
Echo --------------------------- >>D:\Sorted.txt
Find ".wma" D:\Result.txt >>D:\Sorted.txt

etc

A lot more work to setup and is a 2 step process. The solution doesn't look as elegant as either option presented to me either. Thanks for your help.

Upvotes: 1

dbenham
dbenham

Reputation: 130819

The DIR /O sort option works fine when run without the /S option. But when you use the /S option it sorts the results within each directory individually, whereas you want to sort the entire result set.

Bali C's edited answer solves the problem by performing multiple searches individually, one per file extension. He chose to use the FOR command to iterate the files and ECHO the results. I believe it is simpler just to use multiple DIR commands.

>d:result.txt (
  dir /s /b C:\Sample\*.exe
  dir /s /b C:\Sample\*.rar
  dir /s /b C:\Sample\*.mp3
)

or, perhaps a bit less typing

>d:result.txt (
  for %%X in (exe rar mp3) do dir /s /b C:\Sample\*.%%X
)

Upvotes: 0

Bali C
Bali C

Reputation: 31221

Here you go

for %%x in (exe,mp3) do (
for /r C:\Dir %%a in (*.%%x) do echo %%a >>D:\Results.txt
)

Upvotes: 1

Related Questions