Windows cmd show files in directory

I tried searching for a command that could list all the file in a directory as well as subfolders using a command prompt command. I have read the help for "dir" command but coudn't find what I was

I tried searching for a command that could list all the file in a directory as well as subfolders using a command prompt command.
I have read the help for «dir» command but coudn’t find what I was looking for.
Please help me what command could get this.

Martijn Pieters's user avatar

asked Mar 5, 2013 at 1:55

user1760178's user avatar

3

The below post gives the solution for your scenario.

dir /s /b /o:gn

/S Displays files in specified directory and all subdirectories.

/B Uses bare format (no heading information or summary).

/O List by files in sorted order.

Then in :gn, g sorts by folders and then files, and n puts those files in alphabetical order.

Freerey's user avatar

Freerey

1602 silver badges14 bronze badges

answered Mar 5, 2013 at 2:13

5

If you want to list folders and files like graphical directory tree, you should use tree command.

tree /f

There are various options for display format or ordering.

Check example output.

enter image description here

Answering late. Hope it help someone.

answered Aug 24, 2016 at 13:49

Somnath Muluk's user avatar

Somnath MulukSomnath Muluk

53.7k35 gold badges217 silver badges225 bronze badges

7

An addition to the answer: when you do not want to list the folders, only the files in the subfolders, use /A-D switch like this:

dir ..myfolder /b /s /A-D /o:gn>list.txt

micstr's user avatar

micstr

4,8567 gold badges47 silver badges75 bronze badges

answered May 15, 2015 at 9:39

Laszlo Lugosi's user avatar

Laszlo LugosiLaszlo Lugosi

3,5991 gold badge20 silver badges17 bronze badges

4

If you simply need to get the basic snapshot of the files + folders. Follow these baby steps:

  • Press Windows + R
  • Press Enter
  • Type cmd
  • Press Enter
  • Type dir -s
  • Press Enter

answered Jun 21, 2017 at 12:52

Zameer Ansari's user avatar

Zameer AnsariZameer Ansari

27.6k22 gold badges136 silver badges215 bronze badges

2

An alternative to the above commands that is a little more bulletproof.

It can list all files irrespective of permissions or path length.

robocopy "C:YourFolderPath" "C:NULL" /E /L /NJH /NJS /FP /NS /NC /B /XJ

I have a slight issue with the use of C:NULL which I have written about in my blog

https://theitronin.com/bulletproofdirectorylisting/

But nevertheless it’s the most robust command I know.

answered Aug 9, 2017 at 12:56

Bruno's user avatar

BrunoBruno

5,7421 gold badge25 silver badges43 bronze badges

The below post gives the solution for your scenario.

**dir /s /b /o:gn**

/S Displays files in specified directories and all subdirectories.

/B Uses bare format (no heading information or summary).

/O List by files in sorted order.

:gn, g sorts by folders and then files, and n puts those files in alphabetical order.

Just for all files except long path, write the following command:

**dir /b /o:gn**

For Tree:
write in your cmd

tree /f

answered Oct 24, 2022 at 13:23

Tabish Zaman's user avatar

Whenever you want to search and make a list of all files on a specific folder, you used the windows explorer interface to do that. But today in this article we will show other easy ways to that. We will list files using the cmd tool. Command-line provides a simple way to list all the files of a certain type– for example, all your PDF files using the “dir” command. This command will be old news to many but it remains one of the most useful for average PC users. At the end of the post, you will have all switches in order t play with them based on your needs,

How to List all the files in a folder using CMD

  1. Searching on windows the “cmd” name an open as administrator
  2. Navigate to your path where you need to list the file by type cd and the path:
cd c:Test
  1. Click Enter
  2. Execute the following command
dir

Enter “dir” to list the files and folders contained in the folder.

How to List all the files in a folder and subfolder using CMD

If you want to list the files in all the subfolders as well as the main folder, enter:

dir /s

The lists can be quite long and we will create a file containing the list in order to be very easy. You can rename multiple files at once using CMD.

How to list specific file using wildcards

The dir command can also be used to search for specific files and directories by using wildcards. For example, to list files or directories that begin with the letter “B” you could type:

dir b*

To list only the items starting with the B letter.

How to Display Based on File Attributes

You can add “/A” followed by a letter code after the DIR command to display files with a specific attribute. These letter codes include:

  • D: Displays all directories in the current path
  • R: Displays read-only files
  • H: Displays hidden files
  • A: Files that are ready for archiving
  • S: System files
  • I: Not content indexed files
  • L: Reparse points

How to create a text file listing of the files

  1. Open the command line in the folder of interest. Example:
cd c:Test
  1. Execute the following command:
    dir > listoffiles.txt
  2. The command will create a list with the files and folders contained in the folder.
  3. If you want to list the files in all the subfolders as well as the main folder, enter the following command
dir /s >listmyfiles.txt

The file “listoffiles.txt” will be created automatically in the working folder.

Give the full pathname to create the file elsewhere. For example:

dir >D:listmyfiles.txt

Could be used to place the list on an external drive D:

How to create a text file listing only certain types of files

You may want a list of certain types of files such as pdf files. The dir command allows the use of the wildcard symbol *, which adds very useful functionality. Here are some examples.

How to create a list of all the PDF files in a folder and its subfolders:

The command is:

dir /s *.pdf >listpdf.txt

The command will create a list of PDF files only.

A simpler format:

The commands as written will make lists that include information about files such as size and date of creation. A simpler list containing only file names (with full path) can be obtained with the switch “/b”. An example would be:

dir /s/b *.pdf >listpdf.txt

You can also change extension of multiply files using the command line.

How to display only files without folder names

Adding /a-d to the command removes the names of the directories, so all we have are the file names.

dir /a-d /b >..listmyfiles.txt

How to Display Results in Columns

You can use the /D switch to display results in two columns instead of one. When you display results this way, the Command Prompt does not show extra file information (file size and so on)—just the names of the files and directories.

dir /D

How to Display Results in Lowercase

The /L switch displays all names of files and folders as lowercase.

dir /L

Display Results Sorted by Time

Using the /T switch along with a letter code lets you sort results by the different time stamps associated with files and folders. These letter codes include:

  • A:The time the item was last accessed.
  • C:The time the item was created.
  • W:The time the item was last written to. This is the default option used.

So, for example, to sort results by the time items were created, you could use the following command:

dir /TC

All Switches Key

Below are all switches where you can use to create a complex list:

Syntax      DIR [pathname(s)] [display_format] [file_attributes] [sorted] [time] [options]

Key

  • [pathname] The drive, folder, and/or files to display, this can include wildcards:
    • *  – Match any characters
    • ?  – Match any ONE character
  • [display_format]
    • /P   Pause after each screen of data.
    • /W   Wide List format, sorted horizontally.
    • /D   Wide List format, sorted by vertical column.
  • [file_attributes] /A[:]attribute
    • /A:D  Folder         /A:-D  NOT Folder
    • /A:R  Read-only      /A:-R  NOT Read-only
    • /A:H  Hidden         /A:-H  NOT Hidden
    • /A:A  Archive        /A:-A  NOT Archive
    • /A:S  System file    /A:-S  NOT System file
    • /A:I  Not content indexed Files  /A:-I  NOT content indexed
    • /A:L  Reparse Point  /A:-L  NOT Reparse Point (symbolic link)
    • /A:X  No scrub file  /A:-X  Scrub file    (Windows 8+)
    • /A:V  Integrity      /A:-V  NOT Integrity (Windows 8+)
    • /A    Show all files

Several attributes can be combined e.g. /A:HD-R

  • [sorted]   Sorted by /O[:]sortorder
    • /O:N   Name                  /O:-N   Name
    • /O:S   file Size             /O:-S   file Size
    • /O:E   file Extension        /O:-E   file Extension
    • /O:D   Date & time           /O:-D   Date & time
    • /O:G   Group folders first   /O:-G   Group folders last

several attributes can be combined e.g. /O:GEN

  • [time] /T:  the time field to display & use for sorting
    • /T:C   Creation
    • /T:A   Last Access
    • /T:W   Last Written (default)
  • [options]
    • /S     include all subfolders.
    • /R     Display alternate data streams.
    • /B     Bare format (no heading, file sizes, or summary).
    • /L     use Lowercase.
    • /Q     Display the owner of the file.
    • /N     long list format where filenames are on the far right.
    • /X     As for
    • /N but with the short filenames included.
    • /C     Include thousand separator in file sizes.
    • /-C    Don’t include a thousand separators in file sizes.
    • /4     Display four-digit years. In most recent builds of Windows, this switch has no effect.

The number of digits shown is determined by the ShortDate format set in the Control Panel.

Conclusion:

This is all about the methods of how to list files in cmd. Not only but also playing with to get a certain result like export them on a text file or listing only certain types of files.

If you need a list of files in a given directory, for example, so you can loop
through them, how can you get a clean list of file names? On a windows based PC,
you can use dos commands. You’ll need to start by accessing the command line.
Below are directions on how to do that in Windows. Note that if you are using
Stata, you can access the command line by starting the command with a “!” in
other words, do get a list of files in the current directory one would type “!
dir”.

First you’ll need to get to the command prompt, you can do this by going to:

Start -> Run -> Type in “cmd”

final1

This will open the command window. Next I will have to move into the correct
directory. On my computer, the default directory is on the C: drive, but the
folder I want to list the files for is on the D: drive, the first thing I will
see is the prompt “C:>”. The first command below (d:) changes to the D: drive.
The second command moves to the directory d:mydir
which is the directory I want to list the files in. The final line asks for a
listing of the directory, the resulting list of files is shown below.

d:
cd d:mydir
dir

list_files_dir

Now I know I’m in the right directory. The basic command to list the files in
a directory and place them in a text file is seen below, dir indicates
that I want a directory listing, and the >..myfile.txt indicates that I want to place
that listing in a file called myfile.txt one directory above the directory I am listing. (If you do
not use the “..” to place the file in the directory above the current directory, myfile.txt will
be listed along with your other files, which you probably don’t want.)

dir >..myfile.txt

If I open myfile.txt in notepad, I see the following:

 Volume in drive D is New Volume
 Volume Serial Number is 822A-8A09

 Directory of D:mydir

11/15/2007  03:03 PM    <DIR>          .
11/15/2007  03:03 PM    <DIR>          ..
11/15/2007  01:38 PM                 0 10oct2006.txt
11/08/2007  04:28 PM               368 11nov2007.do
11/15/2007  01:39 PM                 0 5june2007.txt
03/11/2007  10:39 AM         1,869,429 beameruserguide.pdf
08/10/2007  01:24 PM            22,016 blog - jsm 2007.doc
04/25/2007  03:07 PM           199,887 clarify.pdf
11/15/2007  01:40 PM                 0 houseplants.txt
04/25/2007  11:42 AM           371,225 Mardia 1970 - multivar skew and kurt.pdf
03/27/2007  01:18 PM           319,864 multiple imputation a primer by schafer.pdf
11/15/2007  02:49 PM                 0 output 1.txt
11/15/2007  02:49 PM                 0 output 2.txt
11/15/2007  02:49 PM                 0 output 3.txt
11/15/2007  02:49 PM                 0 output 4.txt
11/08/2007  03:59 PM             8,514 results.dta
11/15/2007  01:31 PM    <DIR>          sub1
11/15/2007  01:31 PM    <DIR>          sub2
11/14/2007  04:27 PM               952 test.txt
05/21/2007  03:23 PM         1,430,743 zelig.pdf
              18 File(s)      4,225,738 bytes
               4 Dir(s)  249,471,307,776 bytes free

This is a listing of the directory, but it’s not really what I want, there is
too much extra information, so I can add options
to the command to get just the names of the files. Adding /b to the command causes the list
to contain just the file and directory names, not the information on the number of files, when they were
created, etc.. Adding /a-d to the command removes the names of the directories, so all we have
are the file names. (There are a number of other options as well, typing help
dir
will list them. Note that I don’t need to delete myfile.txt to rerun the
command, the old content will automatically be replaced with the output
generated by the new command.

dir /a-d /b >..myfile.txt

now myfile.txt contains:

10oct2006.txt
11nov2007.do
5june2007.txt
beameruserguide.pdf
blog - jsm 2007.doc
clarify.pdf
houseplants.txt
Mardia 1970 - multivar skew and kurt.pdf
multiple imputation a primer by schafer.pdf
output 1.txt
output 2.txt
output 3.txt
output 4.txt
results.dta
test.txt
zelig.pdf

Now suppose I wanted the list to contain only a certain type of file, for example, only text files
with the extension txt. To do this, I can use a wildcard (*) and the file extention to get only files
with the extention .txt . The command below does this.

dir *.txt /a-d /b >..myfile.txt

myfile.txt contains:

10oct2006.txt
5june2007.txt
houseplants.txt
output 1.txt
output 2.txt
output 3.txt
output 4.txt
test.txt

Windows command prompt MS-DOS provides the dir command in order to list files. The dir command provides different features while listing the files. Actually, the dir command does not only list files it also lists directories too. In this tutorial, we will learn how to list files in command prompt in different ways like specific extension, recursive list, etc.

List Files with dir Command

The dir command is a very old command provided by MS-DOS. The dir command is used to list files and folders. Without providing any option to the dir command prints all files and folders in the current directory.

dir
List Files and Folders with dir Command

Only files can be listed by using the /b and /a-d options with dir command. The /b command use bare format where only file names are listed. Also /a-d option is used to not list directories where only files are listed.

dir /b /a-d
List Files with dir Command

Alternatively the bare formattin can be disabled without providing the /b option like below.

dir /a-d
List Files with dir Command

List Files Located in Different Path

Files located different than current working directory or different path can be listed. The path is provided to the dir command as parameter. In the following example we list files located in the C:UsersismailDesktop .

dir C:UsersismailDesktop
List Files in Different Path

Alternatively only files can be listed like below.

dir /b /a-d C:UsersismailDesktop
List Files in Different Path

List File Types

There are a lot of different file types. The dir command can be used to list files according to their types or extension. The extension is used to specify file type. Generally the file extension is specified by using glob operator like *.txt . In the following example we list only zip files using the *.zip .

dir *.zip

Alternatively we can list zip files located other directories by providing the directory path.

dir C:UsersismailDesktop*.zip

List All Files Recursively

By default, the dir lists files located in the current working directory or provided path. It does not list the child directories and child files located in these directories. The /S option can be used to list all files located in the child directories.

dir /S

We can specify the path to list another than the current working directory recursively.

dir /S C:UsersismailDesktop

We can list specific file types recursively. In the following exmaple we list all *.sys files located under the Desktop and its child directories.

dir /S C:UsersismailDesktop*.sys

Updated: 11/06/2021 by

To list or view the files of a directory or folder on your computer, follow the steps below for your operating system.

Show the files in a Windows folder

Microsoft Windows users who want to list files on the computer can open My Computer or Windows Explorer and open the C: drive. Once in the C: drive, all files and folders in the root directory of your primary hard drive are listed.

Tip

In Windows, most of your programs are stored in the Program Files folder, and your documents are frequently saved in the My Documents folder.

Windows File Explorer

Tip

See the Windows command line steps if you are in the Windows command line.

  • How to change a directory or open a folder.

MS-DOS and Windows command line

dir command

To list files while at the MS-DOS prompt or in the Windows command line, use the dir command, as shown below.

The example below is also an example of how the files are listed when using the dir command. See the dir command help page for all the available switches that can be added to this command to perform different functions.

Example of dir command output

Note

By default, the dir command lists the files and directories for the current directory. In the example below, we’re in the Windows directory, so only files and directories in the Windows directory are shown.

C:Windows> dir

Volume in drive C has no label. Volume Serial Number is 6464-D47C Directory of c:windows 04/13/2016 06:24 AM <DIR> . 04/13/2016 06:24 AM <DIR> .. 10/30/2015 01:24 AM <DIR> addins 04/17/2016 07:10 AM 19,326 PFRO.log 10/30/2015 01:18 AM 32,200 Professional.xml 12/23/2015 04:30 AM <DIR> Provisioning 10/30/2015 01:17 AM 320,512 regedit.exe 12/17/2015 08:09 PM <DIR> Registration 04/18/2016 11:28 AM <DIR> rescache 12/17/2015 08:04 PM <DIR> Resources 06/07/2010 03:27 PM 1,251,944 RtlExUpd.dll ... 07/13/2009 11:09 PM 403 win.ini 04/17/2016 07:10 AM <DIR> WinSxS 10/30/2015 01:18 AM 11,264 write.exe 32 File(s) 839,433,436 bytes 81 Dir(s) 341,846,921,216 bytes free

If there are too many files listed in one directory, you can display them one page at a time using the dir command with the /p switch.

dir /p

You can list files that only meet certain criteria using wildcards in the dir command. Below are a few additional examples of the dir command with wildcards.

dir *.txt

In the example above, only files with a file extension of .txt are displayed.

dir a*.*

In the example above, only files that begin with the letter «a» are displayed.

Tip

See our wildcard definition for further information about this term and more examples.

dir c:windows

In the example above, this command lists the files in the C:Windows directory regardless of the current directory or drive.

  • How to use the Windows command line (DOS).
  • How to change a directory or open a folder.

List the files in a Windows PowerShell directory

Like the Windows command line, Windows PowerShell can use the dir command to list files in the current directory. PowerShell can also use the ls and gci commands to list files in a different format.

List the files in a Linux and Unix directory

ls command

To list files in a Linux or Unix command line, use the ls command, as shown below. If you need additional examples and syntax on the ls command, see the ls command help page.

[~/public_html/rss]# ls
./ ../ history.rss issues.rss jargon.rss newjarg.rss newpages.rss newqa.rss

Tip

We recommend using ls -laxo to view files, as it gives you full file information and permission information in an easier to read format.

You can list files that only meet certain criteria using wildcards in the ls command. Below are a few additional examples of the dir command with wildcards.

ls *.txt

In the example above, only files with a file extension of .txt are displayed.

ls r*

In the example above, only files beginning with the letter «r» are displayed.

ls [aeiou]*

In the example above, only files that begin with a vowel (a, e, i, o, u) are displayed.

Tip

See our wildcard definition for further information about this term and additional examples.

ls ~ /public_html

In the example above, the ls command lists all files in the public_html in the home directory (represented by the tilde). If this directory did not exist, you would get an error.

Note

The tilde is a shortcut. Without the shortcut you would need to type the full directory name. For example, if your username was «hope» your home directory would be /home/hope. You can see the full working directory you’re currently in with the pwd command.

  • Linux and Unix shell tutorial.
  • How to change a directory or open a folder.

Show the files on Apple macOS

Apple users can list files through the Finder. If you are in the Terminal, see the Linux steps that also work in the Terminal.

Alternative #1: FOR /R is more intuitive than #2 for me.
Alternative #2: FOR /F fixes the problem with «spaces in names» in BrianAdkins’ suggestion.
Alternative #3: FORFILES would be my pick except that the path is in double quotes.

Brian or other gurus may have a more elegant solution or may be able to suggest a dozen other solutions but these three work. I tried using FOR TOKENS but then had to strip headers and footers so I reverted back to #1. I also considered creating a small .bat file and calling it but that adds another file (although it does provide greater flexibility, as would a function).

I tested all alternatives with directory and filenames with embedded spaces, a 200+ character filename, a filename with no extension, and on root of a small drive (just for time; a little slow — just as Brian suggested — but then so is searching in Windows Explorer; that is why I installed Everything search app).

Alternative #1: FOR /R

Best(?) While trying to figure out why Brian’s solution didn’t work for me I looked at HELP FOR and decided to try the /R approach. (Creating a file would be the same as in Alternative #2.)

@echo off & for /R "c:deletelaterfolder with spaces" %A in (*.*) do echo %~fA %~zA

Example — Works (different directory than above to demonstrate recursion)

@echo off & for /R "c:deletelater" %A in (*.*) do echo %~fA %~zA
c:DeleteLaterName with Spaces.txt 19800676
c:DeleteLaterNoSpacesLongName.txt 21745440
c:DeleteLaterFolder with Spaces2nd Name with Spaces.txt 5805492
c:DeleteLaterFolder with Spaces2ndNoSpacesLongName.txt 3870322
c:DeleteLaterFolderNoSpaces3rd Name with Spaces.txt 27874695
c:DeleteLaterFolderNoSpaces3rdNoSpacesLongName.txt 28726032

Alternative #2: FOR /F

BrianAdkins’ suggested: @echo off & for /f %a in ('dir /s /b') do echo %~fa %~za

A corrected answer is:

@echo off & for /f "delims=*" %A in ('dir /s /b') do echo %~fA %~zA 

A more complete answer with directories suppressed and output (appended) to a file is:

@echo Results on %DATE% for %CD% >> YourDirFile.txt & echo off & for /f "delims=*" %A in ('dir /s /b /a:-d') do echo %~fA %~zA >> YourDirFile.txt

Note: «delims=*» specifies a character not allowed in filenames.
Note: 2nd command also suppresses directories via /a:-d.
Note: Made the FOR variable name uppercase to clarify the distinction between variable and variable parameters if someone chooses different variable names.
Note: Appended to file just for grins as the OP asked for output to a file.

I suppose I should really check the status of ECHO and reset it as well.

Issue — Spaces in Names

Brian’s proposed solution does not handle file and folder names containing spaces (at least not on my Vista configuration).

Example — Wrong
(Without delims; Includes suppressing directory per OP but with size both before and after filename for emphasis)

Truncated Name and Size (4 of 6 files incorrect):

@echo off & for /f %A in ('dir /s /b /a:-d') do echo %~zA %~fA %~zA
 C:DeleteLaterName
21745440 C:DeleteLaterNoSpacesLongName.txt 21745440
 C:DeleteLaterFolder
 C:DeleteLaterFolder
 C:DeleteLaterFolderNoSpaces3rd
28726032 C:DeleteLaterFolderNoSpaces3rdNoSpacesLongName.txt 28726032

Example — Correct
(Note output to screen, not appended to file)

@echo off & for /f "delims=*" %A in ('dir /s /b /a:-d') do echo %~fA %~zA
C:DeleteLaterName with Spaces.txt 19800676
C:DeleteLaterNoSpacesLongName.txt 21745440
C:DeleteLaterFolder with Spaces2nd Name with Spaces.txt 5805492
C:DeleteLaterFolder with Spaces2ndNoSpacesLongName.txt 3870322
C:DeleteLaterFolderNoSpaces3rd Name with Spaces.txt 27874695
C:DeleteLaterFolderNoSpaces3rdNoSpacesLongName.txt 28726032

Alternative #3: FORFILES (Quote Issue)

This solution is straight from the last two examples in the FORFILES documentation (forfiles /?).

FORFILES /S /M *.doc /C "cmd /c echo @fsize"
FORFILES /M *.txt /C "cmd /c if @isdir==FALSE notepad.exe @file"

Combining these examples and writing to a file yields the answer (almost):

forfiles /s  /c "cmd /c if @isdir==FALSE echo @path @fsize" >>ForfilesOut.txt

Note that the path is in quotes in the output.
Does not matter whether echo on or echo off is toggled.
Adding a blank line separating each directory would be a trivial extension of the IF.

Caution: Using the mask /m *.* will not return files without extension (like last file in example)!

Aside: This writes a file in each directory with contents of just that directory:
forfiles /s /c "cmd /c if @isdir==FALSE echo @path @fsize >>ForfilesSubOut.txt" Not what the OP wanted but sometimes handy.

Example — Works (but with fullpath in quotes)

forfiles /s  /c "cmd /c if @isdir==FALSE echo @path @fsize"

"c:DeleteLaterName with Spaces.txt" 19800676
"c:DeleteLaterNoSpacesLongName.txt" 21745440
"c:DeleteLaterFolder with Spaces2nd Name with Spaces.txt" 5805492
"c:DeleteLaterFolder with Spaces2ndNoSpacesLongName.txt" 3870322
"c:DeleteLaterFolderNoSpaces3rd Name with Spaces.txt" 27874695
"c:DeleteLaterFolderNoSpaces3rdNoSpacesLongName.txt" 28726032
"c:DeleteLaterMoreFilesA really really long file name that goes on and on 123456789 asdfghjkl zxcvnm qwertyuiop and still A really really long file name that goes on and on 123456789 qwertyuiop and still further roughly 225 characters by now.txt" 447
"c:DeleteLaterMoreFilesNew Text Document no extension" 0

This example includes an extra directory with a super long filename and a filename with no extension.

Issue: Path in Quotes

So, is there an easy way to remove the unwanted(?) quotes per the OP example and save Alternative #3: FORFILES. (Rhetorical question: Are the quotes a feature or a flaw?)

The dir command is used to list files and folders in the Windows command prompt (CMD).

dir

The dir command without a path will display a list of files and folders in the current working directory.

DIR Command - List Files in Windows Command Prompt

You can provide a path to see the listing for a different directory:

dir C:Windows

By default, the dir command does not show hidden files and folders. To include hidden files, run the dir command as follows:

dir /a

You can use the /B switch to show the file names only without heading information or summary.

dir /b C:Windows

The /s option lists all files in a specified directory and all subdirectories.

dir /s

List Files Using Patterns

The dir command supports wildcard character (*) that you can use to describe a pattern to match.

For example, the following command lists all files that begin with the letter A:

dir a*

Here is another example that lists all files that have a .doc extension:

dir /b *.doc

Displays files with specified attributes

The /A switch is used to list files and folders with specified attributes. For example, the letter H represents the hidden attribute.

dir /a:h

The following table describes each of the values that you can use for Attributes.

D Folders.
H Hidden files and Folders.
S System files.
L Reparse Points.
R Read-only files.
A Files ready for archiving.
I Not content indexed files.
O Offline files.
Prefix meaning not (See examples).

Examples

List Files and folders in C:WindowsSystem32 directory:

dir C:WindowsSystem32

Obtain a listing of all files in C:WindowsSystem32 that ends with the .txt extension:

dir C:WindowsSystem32*.txt

Search for files with .dll extension in C:WindowsSystem32 and all subdirectories:

dir /s C:WindowsSystem32*.dll

Returns the listing for the parent directory of the current working directory:

dir ..

List all files and folders, including hidden files:

dir /a

Show hidden files only:

dir /a:h

List only folders:

dir /a:d

Don’t list folders:

dir /a:-d

Show only hidden folders:

dir /a:dh

List read only files:

dir /a:r

Sort the result by name:

dir /o:n

This will sort the result set by size:

dir /o:s

Sort the result set by size (largest first):

dir /o:-s

Sort the result by date:

dir /o:d

Includes the name of the owner for each file:

dir /q

Show creation time:

dir /t:c

Show last access time:

dir /t:a

Show the last written time:

dir /t:w

Run the dir /? command to see a list of all the available command-line options.

Получение списка файлов из папки в WindowsКогда ко мне обратились с вопросом о том, как быстро вывести список файлов в текстовый файл, я понял, что ответа я не знаю. Хотя задача, как оказалось, достаточно часто встречающаяся. Это может потребоваться для передачи списка файлов специалисту (для решения какой-то проблемы), самостоятельного ведения журнала содержимого папок и других целей.

Решено было устранить пробел и подготовить инструкцию на эту тему, в которой будет показано, как получить список файлов (и вложенных папок) в папке Windows средствами командной строки, а также о том, как автоматизировать этот процесс, если задача возникает часто.

Получение текстового файла с содержимым папки в командной строке

Получение списка файлов в командной строке

Сначала о том, как сделать текстовый документ, содержащий список файлов в нужной папке, вручную.

  1. Запустите командную строку от имени администратора.
  2. Введите cd x:folder где x:folder — полный путь к папке, список файлов из которой нужно получить. Нажмите Enter.
  3. Введите команду dir /a /-p /o:gen >files.txt (где files.txt — текстовый файл, в котором будет сохранен список файлов). Нажмите Enter.
  4. Если использовать команду с параметром /b (dir /a /b /-p /o:gen >files.txt), то в полученном списке будет отсутствовать любая дополнительная информация о размерах файлов или дате создания — только список имен.

Готово. В результате будет создан текстовый файл, содержащий необходимую информацию. В команде выше, данный документ сохраняется в той же папке, список файлов из которой требуется получить. Можно также убрать вывод в текстовый файл, в этом случае список будет отображаться только в командной строке.

Полученный текстовый файл со списком

Кроме этого, для пользователей русскоязычной версии Windows следует учитывать то, что файл сохраняется в кодировке Windows 866, то есть в обычном блокноте вместо русских символов вы увидите иероглифы (но можно использовать альтернативный текстовый редактор для просмотра, например, Sublime Text).

Получаем список файлов с помощью Windows PowerShell

Вы также можете получить список файлов в папке используя команды Windows PowerShell. Если вы хотите сохранить список в файл, то запустите PowerShell от имени администратора, если просто просмотреть в окне — достаточно простого запуска.

Сохранение списка файлов в текстовый файл в PowerSehll

Примеры команд:

  • Get-Childitem -Path C:Folder — вывод списка всех файлов и папок, находящихся в папке Folder на диске C в окне Powershell.
  • Get-Childitem -Path C:Folder | Out-File C:Files.txt — создание текстового файла Files.txt со списком файлов в папке Folder.
  • Добавление параметра -Recurse к первой описанной команде выводит в списке также содержимое всех вложенных папок.
  • Параметры -File и -Directory позволяют получить список только файлов или только папок соответственно.

Список файлов, полученный в PowerShell

Выше перечислены далеко не все параметры Get-Childitem, но в рамках описываемой в этом руководстве задачи, думаю, их будет достаточно.

Утилита Microsoft Fix it для печати содержимого папки

На странице https://support.microsoft.com/ru-ru/kb/321379 присутствует утилита Microsoft Fix It, добавляющая в контекстное меню проводника пункт «Print Directory Listing», выводящий список файлов в папке на печать.

Вывод списка файлов на печать через контекстное меню

Несмотря на то, что программа предназначена только для Windows XP, Vista и Windows 7, она успешно сработала и в Windows 10, достаточно было запустить ее в режиме совместимости.

Дополнительно, на той же странице показан порядок ручного добавления команды вывода списка файлов в проводник, при этом вариант для Windows 7 подойдет и для Windows 8.1 и 10. А если вам не требуется вывод на печать, вы можете немного подправить предлагаемые Microsoft команды, удалив параметр /p в третьей строке и полностью убрав четвертую.

Like this post? Please share to your friends:
  • Windows cannot connect to the printer 0x00000002
  • Windows cmd replace string in file
  • Windows cannot complete the password change for
  • Windows cmd remove directory with files
  • Windows cannot complete the extraction что это