Программистам часто приходится работать в консоли — например, чтобы запустить тестирование проекта, закоммитить новый код на Github или отредактировать документ в vim. Всё это происходит так часто, что все основные действия с файлами становится быстрее и привычнее выполнять в консоли. Рассказываем и показываем основные команды, которые помогут ускорить работу в терминале под OS Windows.
Для начала нужно установить терминал или запустить командную строку, встроенную в Windows — для этого нажмите Win+R
и введите cmd
. Терминал часто встречается и прямо в редакторах кода, например, в Visual Studio Code.
Чтобы ввести команду в консоль, нужно напечатать её и нажать клавишу Enter
.
Содержимое текущей папки — dir
Выводит список файлов и папок в текущей папке.
C:\content-server>dir
Том в устройстве C имеет метку SYSTEM
Серийный номер тома: 2C89-ED9D
Содержимое папки C:\content-server
06.10.2020 00:41 <DIR> .
06.10.2020 00:37 <DIR> .circleci
16.07.2020 16:04 268 .editorconfig
16.07.2020 16:04 10 .eslintignore
16.07.2020 16:04 482 .eslintrc
06.10.2020 00:37 <DIR> .github
16.07.2020 16:04 77 .gitignore
06.10.2020 00:41 <DIR> assets
06.10.2020 00:41 <DIR> gulp
16.07.2020 16:10 379 gulpfile.js
16.07.2020 16:10 296 320 package-lock.json
16.07.2020 16:10 751 package.json
16.07.2020 16:04 509 README.md
Открыть файл
Чтобы открыть файл в текущей папке, введите его полное имя с расширением. Например, blog.txt или setup.exe.
Перейти в другую папку — cd
Команда cd
без аргументов выводит название текущей папки.
Перейти в папку внутри текущего каталога:
C:\content-server>cd assets
C:\content-server\assets>
Перейти на одну папку вверх:
C:\content-server\assets>cd ..
C:\content-server>
Перейти в папку на другом диске:
c:\content-server>cd /d d:/
d:\>
Чтобы просто изменить диск, введите c:
или d:
.
Создать папку — mkdir или md
Создаём пустую папку code
внутри папки html
:
d:\html>mkdir coded:\html>dir
Содержимое папки d:\html
03.11.2020 19:23 <DIR> .
03.11.2020 19:23 <DIR> ..
03.11.2020 19:25 <DIR> code
0 файлов 0 байт
3 папок 253 389 438 976 байт свободно
Создаём несколько пустых вложенных папок — для этого записываем их через косую черту:
d:\html>mkdir css\js
d:\html>dir
Том в устройстве D имеет метку DATA
Серийный номер тома: 0000-0000
Содержимое папки d:\html
03.11.2020 19:23 <DIR> .
03.11.2020 19:23 <DIR> ..
03.11.2020 19:25 <DIR> code
03.11.2020 19:29 <DIR> css
Создаётся папка css
, внутри которой находится папка js
. Чтобы проверить это, используем команду tree
. Она показывает дерево папок.
Удалить папку — rmdir или rd
Чтобы удалить конкретную папку в текущей, введите команду rmdir
:
d:\html\css>rmdir js
При этом удалить можно только пустую папку. Если попытаться удалить папку, в которой что-то есть, увидим ошибку:
d:\html\css>d:\html>rmdir css
Папка не пуста.
Чтобы удалить дерево папок, используйте ключ /s
. Тогда командная строка запросит подтверждение перед тем, как удалить всё.
d:\html>rmdir css /s
css, вы уверены [Y(да)/N(нет)]? y
Показать дерево папок — tree
В любом момент мы можем увидеть структуру папок. Для этого используется команда tree
.
d:\html>tree
Структура папок тома DATA
Серийный номер тома: 0000-0000
D:.
├───code
└───css
└───js
Если вы хотите посмотреть содержимое всего диска, введите tree
в корне нужного диска. Получится красивая анимация, а если файлов много, то ещё и немного медитативная.
Удаление файла — del или erase
Команда для удаления одного или нескольких файлов.
d:\html>del blog.txt
Переименование файла — ren или rename
Последовательно вводим ren
, старое и новое имя файла.
d:\html>dir
Содержимое папки d:\html
03.11.2020 19:23 <DIR> .
03.11.2020 19:23 <DIR> ..
03.11.2020 19:59 0 blag.txt
d:\html>ren blag.txt blog.txt
d:\html>dir
Содержимое папки d:\html
03.11.2020 19:23 <DIR> .
03.11.2020 19:23 <DIR> ..
03.11.2020 19:59 0 blog.txt
Команды одной строкой
Очистить консоль — cls
.
Информация о системе — systeminfo
.
d:\html>systeminfo
Имя узла: DESKTOP-6MHURG5
Название ОС: Майкрософт Windows 10 Pro
Версия ОС: 10.0.20246 Н/Д построение 20246
Изготовитель ОС: Microsoft Corporation
Параметры ОС: Изолированная рабочая станция
Сборка ОС: Multiprocessor Free
Информация о сетевых настройках — ipconfig
.
d:\html>ipconfig
Настройка протокола IP для Windows
Адаптер Ethernet Ethernet 2:
Состояние среды. . . . . . . . : Среда передачи недоступна.
DNS-суффикс подключения . . . . . :
Список запущенных процессов — tasklist
.
c:\>tasklist
Имя образа PID Имя сессии № сеанса Память
========================= ======== ================ =========== ============
System Idle Process 0 Services 0 8 КБ
System 4 Services 0 2 688 КБ
Secure System 72 Services 0 23 332 КБ
…
Справка по командам — help
Команда help
без аргументов выводит список всех возможных команд. help
вместе с именем команды выведет справку по этой команде.
d:\html>help tree
Графическое представление структуры папок или пути.
TREE [диск:][путь] [/F] [/A]
/F Вывод имён файлов в каждой папке.
/A Использовать символы ASCII вместо символов национальных алфавитов.
В этой статье приведены не все команды и не все их возможности, но вы всегда можете воспользоваться командой help
и узнать о том, что ещё может командная строка.
👉🏻 Больше статей о фронтенде и работе в айти в телеграм-канале.
Подписаться
Материалы по теме
- 10 горячих клавиш VS Code, которые ускорят вашу работу
- Полезные команды для работы с Git
- Полезные команды для работы с Node. js
«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.
ТелеграмПодкастБесплатные учебники
Last Updated :
06 Mar, 2025
Struggling to find or organize files buried in folders on your Windows PC? While File Explorer offers a visual way to browse, the Command Prompt (CMD) provides a faster, more powerful method to list, sort, and manage files, especially when dealing with large directories or automating tasks.
In this quick guide on how to list all files in a directory using CMD in Windows, you will explore how to use simple CMD commands like dir to instantly display every file and subfolder in any directory. We’ll break down the syntax, explain how to filter results (by name, date, or type), and share tricks to export lists for backups.
Prerequisites to Access Directory in Win
- Windows PC (11, 10, 8 or 7)
- Administrator Rights
- Familiar with Command Prompt actions (or knowing how to open it, i.e. Win + R & type CMD)
What Command Can Be Used to List Files
The «dir» command is fundamental in the Windows Command Prompt, which is used to list the contents of a directory. Here’s a bit more detail on how it works.
1. Basic Usage
- When you type dir and press Enter in the Command Prompt, it lists all the files and directories in the current directory.
- By default, it displays the file name, size, and modification date and time.
2. Options
- /A: This option displays files with specified attributes. For example, /A: H displays hidden files.
- /B: Uses a bare format with no heading information or summary. It simply lists the names of files and directories.
- /O: Specifies the order in which files are sorted. For instance, /O: N sorts files by name.
- /S: Displays files in the specified directory and all subdirectories.
- /P: Pauses after each screenful of information.
- /W: Uses wide list format, displaying as many as five file names in each row.
3. Example Usage
- dir /A: Lists all files including hidden files in the current directory.
- dir /B: Displays a bare list of files and directories without any additional information.
- dir /O:N: Sorts files by name.
- dir /S: Lists files in the specified directory and all subdirectories.
How to List All Files in a Directory
Now, we will be discussing 4 basic steps to list all files in a directory using the Command Prompt. Let’s check them out:
Step 1: Open Command Prompt
- First things first, let’s open the Command Prompt. You can do this by searching for «Command Prompt» in the Start menu or by pressing the Win + R keys, typing «cmd» in the «Run» dialog, and hitting Enter.
Step 2: Navigate to the Directory
- Once you have the Command Prompt open, you need to navigate to the directory whose files you want to list. To do this, use the cd command followed by the path of the directory. For example, if you want to list files in a directory named «Documents» located in your user folder, you would type:
cd Documents
Press Enter after typing the command to change the directory.
Step 3: List Files
- Now that you’re in the desired directory, it’s time to list all the files it contains. To do this, simply type the «dir» command and press Enter. This command displays a list of files and directories in the current directory.
Step 4: Additional Options (Optional)
- If you want to customize the way files are listed, you can use various options with the dir command. Here are some common options:
/A: Displays files with specified attributes.
/B: Uses bare format (no heading information or summary).
/O: Specifies the order in which files are sorted.
/S: Displays files in specified directory and all subdirectories.
For example, if you want to list all files including hidden files in bare format, you would type:
dir /A /B
Use Cases for Listing Files in CMD
- IT Audits: Export a list of all
.exe
files in a directory for compliance checks. - Scripting Backups: Automate file logging with a batch script.
- Troubleshooting: Identify missing or corrupted files in large folders.
CMD vs PowerShell: Which One to Use
Task | CMD Command | PowerShell Equivalent |
---|---|---|
List files | dir |
Get-ChildItem |
Filter by date | dir /od |
Get-ChildItem | Sort LastWriteTime |
Export to text file | dir > output.txt |
Get-ChildItem > output.txt |
Conclusion
Mastering the dir command in CMD lets you efficiently manage files, automate tasks and troubleshoot Windows system within a few steps. By following the outline steps, you can use the Command Prompt to organize your workspace or troubleshooting, without replying on graphical interfaces. Whether you’re an IT expert, a developer (for scripting batch jobs) or a casual user organizing personal documents, the ability to list files in a directory using CMD is a must-know job that everyone should know.
Also Read
- CMD | Dir command
- How to Delete a File or Folder Using CMD?
- Search Files Faster on Windows 10 using Command Prompt
- Use the “DIR” command to list files and folders in the current directory, or “DIR /S” to list files and folders recursively, in subdirectories as well.
- To search for specific file types use the asterisk followed by the file extension type, in this syntax: DIR *.jpg
- Use attribute switches to filter the type of files and folders to list.
It can be tricky to keep tabs on all files and folders on a Windows computer, especially if there are too many. There can be many folders and subfolders inside a partition, and many different types of file extensions. It can be difficult to view all the files and folders, or even search for specific ones using File Explorer.
Using the Command Prompt, you can view and list all sorts of files and folders inside a directory, and even its subdirectories using recursive switches. Not only that, but you can also list all items with a specific file type, or exclude them. Moreover, you can also view hidden items as well directly from the Command Prompt.
In this article, we give you a bunch of different examples to list files and folders inside the Command Prompt using the DIR cmdlet.
Command to List Files and Folders in Command Prompt
The DIR command is used to list files and folders inside a directory in Command Prompt. This command can be used with a number of switches and attributes to filter the items to display, their order or displaying, to include and exclude, and so on.
However, the only switches we will be interested in are /a and /s.
Using the DIR
command alone will display all the files and folders inside that particular directory. It will not show any hidden items, and it will now show any items inside the subdirectories. However, if you use DIR /a
, it will show the hidden items as well.
To perform a recursive search, we must use the /s
switch.
The table below summarises the commands to use to list files and folders and these switches:
Command | Description |
DIR | Display items inside the current directory |
DIR /a | Display all items inside the current directory, including hidden ones. |
DIR /s | List items inside the current directory as well as all subdirectories |
With that known, there is a list of attributes that you can use with the DIR /a
cmdlet to filter the type of information you want to list. Here is a list of the attributes you can use with /a
.
Attribute Alphabet | Description | Syntax Example |
d | Shows directories only | DIR /ad |
h | Show hidden items only | DIR /ah |
s | Show system files only | DIR /as |
l | Show reparse points only | DIR /al |
r | Show read-only files | DIR /ar |
a | Show files that can be archived | DIR /aa |
i | Show files whose content is not indexed | DIR /ai |
– (hyphen) | Used before an attribute to exclude it from the list | DIR /a-s (hide system files) |
: (colon) | To combine multiple attributes | DIR /a:h-s (Show hidden items but hide system files) |
Example Commands to List Files and Folders in Command Prompt
Let us now continue to see more extensive examples with images to better understand how you can list files and folders using the DIR
cmdlet.
-
To list all files and folders in the current directory:
DIR
List files and folders in the current directory using Command Prompt -
To list all files and folders in the current directory and subdirectories:
DIR /S
List recursive files and folders in Command Prompt -
To list only folders in the current directory:
DIR /AD
List only folders in the current directory in Command Prompt -
To list only folders in the current directory and subdirectories:
DIR /AD /S
List only folders in the current directory and subdirectories in Command Prompt -
To list all files in the current directory and exclude all folders:
DIR /A-D
List all files and exclude folders in the current directory in Command Prompt -
To list all hidden system files in the current directory:
DIR /ASH
List all hidden system files in current directory in Command Prompt -
To list all system files and exclude read-only files in the current directory and subdirectories:
DIR /A:S-A /S
List all system files and exclude read-only files in the current directory and subdirectories using Command Prompt -
To list all specific file type files in the current directory and subdirectories:
Note: You can change the file type extension to list the files you are looking for.
DIR *.txt
List all files with a specific file type using Command Prompt -
To list multiple file types in the current directory and subdirectories:
DIR *.txt *.doc *.docx /S
List multiple file types in the current directory and subdirectories from Command Prompt
There can be many different examples and syntaxes to list files and folders inside the Command Prompt. However, we hope that the examples above are sufficient so that you can combine and modify them as per your requirements.
Closing Words
The Windows command line offers much more control over the fetched data than its GUI. Using the Command Prompt, you can list different files and folders inside the current directory as well as its subdirectories. You can also filter out the type of files and folders to include, or exclude from the list.
Когда ко мне обратились с вопросом о том, как быстро вывести список файлов в текстовый файл, я понял, что ответа я не знаю. Хотя задача, как оказалось, достаточно часто встречающаяся. Это может потребоваться для передачи списка файлов специалисту (для решения какой-то проблемы), самостоятельного ведения журнала содержимого папок и других целей.
Решено было устранить пробел и подготовить инструкцию на эту тему, в которой будет показано, как получить список файлов (и вложенных папок) в папке Windows средствами командной строки, а также о том, как автоматизировать этот процесс, если задача возникает часто.
Получение текстового файла с содержимым папки в командной строке
Сначала о том, как сделать текстовый документ, содержащий список файлов в нужной папке, вручную.
- Запустите командную строку от имени администратора.
- Введите cd x:\folder\ где x:\folder\ — полный путь к папке, список файлов из которой нужно получить. Нажмите Enter.
- Введите команду dir /a /-p /o:gen >files.txt (где files.txt — текстовый файл, в котором будет сохранен список файлов). Нажмите Enter.
- Если использовать команду с параметром /b (dir /a /b /-p /o:gen >files.txt), то в полученном списке будет отсутствовать любая дополнительная информация о размерах файлов или дате создания — только список имен.
Готово. В результате будет создан текстовый файл, содержащий необходимую информацию. В команде выше, данный документ сохраняется в той же папке, список файлов из которой требуется получить. Можно также убрать вывод в текстовый файл, в этом случае список будет отображаться только в командной строке.
Кроме этого, для пользователей русскоязычной версии Windows следует учитывать то, что файл сохраняется в кодировке Windows 866, то есть в обычном блокноте вместо русских символов вы увидите иероглифы (но можно использовать альтернативный текстовый редактор для просмотра, например, Sublime Text).
Получаем список файлов с помощью Windows PowerShell
Вы также можете получить список файлов в папке используя команды Windows PowerShell. Если вы хотите сохранить список в файл, то запустите PowerShell от имени администратора, если просто просмотреть в окне — достаточно простого запуска.
Примеры команд:
- Get-Childitem -Path C:\Folder — вывод списка всех файлов и папок, находящихся в папке Folder на диске C в окне Powershell.
- Get-Childitem -Path C:\Folder | Out-File C:\Files.txt — создание текстового файла Files.txt со списком файлов в папке Folder.
- Добавление параметра -Recurse к первой описанной команде выводит в списке также содержимое всех вложенных папок.
- Параметры -File и -Directory позволяют получить список только файлов или только папок соответственно.
Выше перечислены далеко не все параметры 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 в третьей строке и полностью убрав четвертую.
on August 9, 2009
dir
command can be used to list the files from command prompt. This article explains the syntax for different usecases.
- A simple
dir
command without any other arguments lists all the files/subfolders that exist in the current folder.dir
- Lists the subfolders/files names in bare format.
dir /b
This command prints the file names. No other file meta data like file modified time, file size etc are not displayed.
- List the files in the current folder and also the ones in the subfolders recursively.
dir /s
Using wild cards with dir
Dir command accepts wild cards to display information only for the files that match the pattern specified. The below examples illustrate different use cases where we can use these wild cards
- List files of certain type or based on extension
For example to list all jpeg files in the current folder, we can run the below command.dir *.jpeg
To list all excel files
dir *.xls
We can even specify multiple extension in dir command to list files of any of the types. To list all files created with Office applications like Word, Excel, Powerpoint etc we can run below command.
dir *.docx *.xlsx *.pptx
- List files beginning/ending with specific pattern
List all files in the current folder whose names begin with ‘Picture-‘dir /S Picture-*
List file names based on type
dir command can list the file names and also the subfolders names. We can be selective and say that we want only names of the files to be listed or only the names of the subdirectories to be listed.
- List only directories
dir /A:D
- List only files
dir /A:-D
Display files based on file attributes
We can filter out which files should be listed in the dir
command output based on read-only, system, hidden archive file attributes.
- For example, to list read-only files in the current directory, the command is:
dir /A:R
- Similarly to display hidden files
dir /A:H
- For the opposite case of looking for files where an attribute is not set, we can append
'-'
to the attribute code. For example, to print the file names without archive attribute set, we can use the below command.dir /A:-A
- Exclude Read-only files from the listing.
dir /A:-R
- Exclude hidden files from listing.
dir /A:-H
- Exclude system files from listing
dir /A:-S
Print metadata of files using dir command
- Find out who owns a file
dir /Q
Example:
c:\>dir /Q 1.txt 05/03/2015 01:12 AM 151,906 BUILTIN\Administrators 1.txt
The above result of dir indicates that file 1.txt is owned by Administrators group.
- Get created time of a file
dir /TC
- Find last accessed time of a file
dir /TA
- Find last modified time of a file
dir /TW