Команда dir в командной строке windows

Программистам часто приходится работать в консоли — например, чтобы запустить тестирование проекта, закоммитить новый код на 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

«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.

ТелеграмПодкастБесплатные учебники

  • 01.11.2020
  • 13 510
  • 0
  • 14
  • 14
  • 0

DIR - описание команды и примеры использования

  • Содержание статьи
    • Описание
    • Синтаксис
    • Параметры
    • Примечания
    • Примеры использования
    • Справочная информация
    • Добавить комментарий

Описание

DIR — Выводит список файлов и подкаталогов каталога. Вызванная без параметров команда dir выводит метку тома и серийный номер, за которыми следует список каталогов и файлов на диске, включая их имена, дату и время последнего изменения. Для файлов dir выводит также расширение имени и размер в байтах. Команда dir также выводит общее число перечисленных файлов и каталогов, их общий размер и свободное пространство (в байтах) на диске.

Синтаксис

dir [диск:][путь][имя_файла] [...] [/p] [/q] [/w] [/d] [/a[[:]атрибуты]][/o[[:]порядок_сортировки]] [/t[[:]поле_сортировки]] [/s] [/b] [/l] [/n] [/x] [/c] [/4]

. . . . . . .

Параметры

Параметр Описание
[диск:][путь] Задание диска и каталога, список файлов которого будет выведен
[имя_файла] Задание файла или группы файлов, сведения о которых требуется вывести
/p Постраничный вывод сведений, т. е. с паузой после заполнения экрана. Для продолжения просмотра необходимо нажать любую клавишу
/q Вывод сведений о владельце файла
/w Вывод сведений в несколько колонок до пяти имен файлов или каталогов в каждой строке
/d Соответствует /w, но с сортировкой по столбцам
/a [[:] атрибуты] Выводит имена только тех файлов и каталогов, которые имеют указанные атрибуты. Если параметр /a не указан, команда dir выводит имена всех файлов, за исключением системных и скрытых. Если параметр /a указан без атрибутов, команда dir выводит имена всех файлов, включая скрытые и системные. Ниже приведен список значений, которые могут быть использованы при задании параметра атрибуты. Двоеточие (:) является необязательным. Значения из таблицы могут использоваться в любых комбинациях без пробела между ними.
h — Скрытые файлы
s — Системные файлы
d — Каталоги
a — Файлы, готовые к архивированию
r — Файлы, доступные только для чтения
-h — Файлы, не являющиеся скрытыми
-s — Файлы, не являющиеся системными
-d — Только файлы (не каталоги)
-a — Файлы, не изменявшиеся после последнего архивирования
-r — Файлы, не имеющие атрибута «Только чтение»
/o [[:]порядок_сортировки] Управление порядком сортировки и вывода имен файлов и каталогов командой dir. Если параметр /o, не задан, команда dir выводит имена в том порядке, в котором они записаны в каталоге. Если параметр /o использован без параметра порядок_сортировки, команда dir выводит имена каталогов в алфавитном порядке, затем — имена файлов в алфавитном порядке. Двоеточие (:) является необязательным. Ниже приведен список значений, которые могут быть использованы при задании параметра порядок_сортировки. Допускается использование любого их сочетания без пробелов между ними.
n — Сортировка по именам в алфавитном порядке
e — Сортировка по расширениям в алфавитном порядке
d — Сортировка по дате и времени от ранних к поздним
s — Сортировка по размеру от меньших к большим
g — Сортировка с группированием каталогов перед файлами
-n — Сортировка по именам в обратном алфавитном порядке (от Z к A)
-e — Сортировка по расширению в обратном алфавитном порядке (от .ZZZ к .AAA)
-d — Сортировка по дате и времени от поздних к ранним
-s — Сортировка по размеру от больших к меньшим
-g — Сортировка с группировкой каталогов после файлов
/t [[:]поле_времени] Задание поля времени для вывода и сортировки. Ниже приведен список значений, которые могут быть использованы при задании параметра поле_времени.
c — Создание
a — Последнее обращение
w — Последняя запись
/s Перечисление всех случаев обнаружения определенного имени файла в указанном каталоге и всех его подкаталогах
/b Перечисление каждого имени файла (включая расширение) или каталога на отдельной строке. При использовании параметра /b заголовочные сведения или сводка не выводятся. Параметр /b отменяет параметр /w
/l Вывод несортированного списка имен каталогов и имен файлов строчными буквами. Параметр /l не позволяет преобразовывать дополнительные символы в строчные
/n Вывод списка в расширенном формате с именами файлов в правой части экрана
/x Вывод сокращенных имен файлов файловых систем NTFS и FAT. Формат совпадает с форматом параметра /n, но сокращенные имена выводятся после полных
/c Вывод разделителя десятичных разрядов в размере файлов
/4 Отображение года в четырехзначном формате
/? Отображение справки в командной строке

Примечания

  • Использование нескольких имен_файлов Допускается использование нескольких имен_файлов. Разделяйте имена файлов пробелом, запятой или точкой с запятой. Для вывода группы файлов допускается применение подстановочных знаков (? и *) в параметре имя_файла.
  • Использование подстановочных знаков. Для вывода списка подгруппы файлов и подкаталогов можно использовать подстановочные знаки (? и *).
  • Задание атрибутов файлов для вывода. Если параметр /a используется более чем с одним значением параметра атрибуты, команда dir выведет имена только тех файлов, все атрибуты которых совпадают с заданными. Например, при использовании параметра /a со значениями атрибутов r и -h в формате /a:r-h или /ar-h команда dir выведет имена файлов, являющихся одновременно скрытыми и защищенными от записи.
  • Указание порядка сортировки имен файлов. Если указано несколько значений порядка_сортировки, команда dir сортирует имена файлов сначала по первому условию, затем — по второму и т. д. Например, если указан ключ /o со значениями e и -s порядка_сортировки в формате /o:e-s или /oe-s, команда dir отсортирует имена каталогов и файлов по расширениям, затем от больших файлов к меньшим и выведет окончательный результат. В результате сортировки по алфавиту файлы без расширений будут идти вначале, затем имена каталогов, а потом имена файлов с расширениями.
  • Использование перенаправления и каналовЧтобы перенаправить вывод команды dir в файл с помощью символа (>) или использовать канал (|) для передачи вывода в другую команду, необходимо использовать параметры команды dir /a:-d и /b для вывода только списка имен файлов. Параметр имя_файла с параметрами /b и /s можно использовать, чтобы указать поиск командой dir в текущем каталоге и его подкаталогах всех файлов, соответствующих значению имя_файла. При этом команда dir выведет только имя диска, имя каталога, имя файла и расширение по одному файлу в строке. Чтобы использовать перенаправление с помощью каналов, в файле Autoexec.nt должна быть установлена переменная среды TEMP.
  • Предварительное задание параметров команды dir. Параметры команды dir могут быть предварительно заданы включением команды set для переменной среды DIRCMD в файл Autoexec.nt. В команде set dircmd может быть использована любая допустимая комбинация параметров команды dir, включая расположение и имя файла.Например, чтобы использовать переменную среды DIRCMD для задания вывода в расширенном формате (/w) по умолчанию, в файле Autoexec.nt необходимо ввести следующую строку:set dircmd=/w При однократном использовании команды dir можно отменить параметр с помощью переменной среды DIRCMD. Для этого введите параметр, который требуется отменить, в командной строке dir, указав перед ним знак минус. Например:

    dir /-w

    Чтобы изменить параметры DIRCMD, используемые по умолчанию, введите следующую команду:

    set=новый_параметр

    Новые параметры по умолчанию останутся в силе для всех последующих команд dir, пока команда set dircmd не задаст новые параметры или не будет перезагружен компьютер.

    Чтобы удалить все параметры по умолчанию, введите следующую команду:

    set dircmd=

    Чтобы просмотреть текущие параметры переменной среды DIRCMD, введите следующую команду:

    set

  • Команда dir с другими параметрами доступна в консоли восстановления.

Примеры использования

Чтобы вывести подряд все каталоги в алфавитном порядке, в несколько колонок и с паузой после заполнения каждого экрана, убедитесь, что корневой каталог является текущим, и введите следующую команду:

dir /s/w/o/p

Команда dir выводит имя корневого каталога, имена его подкаталогов и имена файлов (включая расширения) в этом каталоге. Затем выводятся имена подкаталогов и имена файлов в каждом каталоге дерева каталогов.
Для изменения предыдущего примера так, чтобы команда dir не выводила имена каталогов, введите следующую команду:

dir /s/w/o/p/a:-d

Чтобы напечатать список каталогов, введите следующую команду:

dir > prn

Если указать параметр prn, список каталогов отправляется на принтер, подключенный к порту LPT1. Если принтер подключен к другому порту, необходимо заменить параметр prn именем этого порта.

Вывод команды dir также может быть направлен в файл при замене prn на имя файла. Кроме того, можно также ввести путь. Например, для направления вывода команды dir в файл Dir.doc в каталоге Records введите следующую команду:

dir > \records\dir.doc

Если файл Dir.doc не существует, команда dir создаст его при условии наличия каталога Records. Если этот каталог не существует, выводится следующее сообщение:

Ошибка создания файла

Чтобы вывести список всех файлов с расширением .txt во всех каталогах диска C, введите следующую команду:

dir c:\*.txt /w/o/s/p

Команда dir выводит на экран алфавитный список файлов, удовлетворяющих заданному шаблону, в несколько колонок с паузой после заполнения каждого экрана.

Справочная информация

The dir command is a Command Prompt command used to display a list of the files and subfolders contained in a folder.

For each file or folder listed, the command will, by default, show the date and time the item was last changed, if the item is a folder (labeled with DIR) or file, the size of the file if applicable, and finally the name of the file or folder including the file extension.

Theresa Chiechi / Lifewire

Outside of the file and folder list, the dir command also displays the current drive letter of the partition, the volume label, volume serial number, total number of files listed, total size of those files in bytes, the number of subfolders listed, and the total bytes remaining free on the drive.

Dir Command Availability

The dir command is available from within the Command Prompt in all Windows operating systems including Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.

Older versions of Windows include the dir command as well but with a few fewer options than we have listed below. The dir command is also a DOS command, available in all versions of MS-DOS.

The dir command can be found in offline Command Prompt versions, like the ones available from Advanced Startup Options and System Recovery Options. The dir command is also included in the Recovery Console in Windows XP.

The availability of certain dir command switches and other dir command syntax may differ from operating system to operating system.

Dir Command Syntax

dir [drive:][path][filename] [/a[[:]attributes]] [/b] [/c] [/d] [/l] [/n] [/o[[:]sortorder]] [/p] [/q] [/r] [/s] [/t[[:]timefield]] [/w] [/x] [/4]

See How to Read Command Syntax if you’re not sure how to interpret the syntax of the dir command as it’s written above or shown in the table below.

Dir Command Options
Item Explanation
drive:, path, filename This is the drive, path, and/or filename that you want to see results for. All three are optional since the command can be executed alone. Wildcards are allowed. See the Dir Command Examples section below if this isn’t clear.
/a

When executed alone, this switch shows all types of files and folders, including those with file attributes that typically prevent them from showing up in Command Prompt or in Windows. Use /a with one or more of the following attributes (colon is optional, no spaces needed) to show only those types of files in the command result:

a = archive files

d = directories

h = hidden files

i = not content indexed files

l = reparse points

r = read-only files

s = system files

v = integrity files

x = no scrub files

= Use this as a prefix to any of the above attributes to exclude items with those file attributes from the results.

/b Use this option to show the dir results using «bare» format, which removes the typical header and footer information, as well as all the details on each item, leaving only the directory name or file name and extension.
/c This switch forces the use of the thousands separator when the command is used in a way that shows file sizes. This is the default behavior on most computers, so the practical use is /-c to disable the thousands separator in results.
/d Use /d to limit the items displayed to just folders (contained within brackets) and file names with their extensions. Items are listed top-to-bottom and then across columns. Standard dir command header and footer data remain the same.
/l Use this option to show all folder and file names in lowercase.
/n This switch produces a result with columns in the date > time > directory > file size > file or folder name column structure. Since this is the default behavior, the practical use is /-n which produces columns in the file or folder name > directory > file size > date > time order.
/o

Use this option to specify a sort order for the results. When executed alone, /o lists directories first, followed by files, both in alphabetical order. Use this option with one or more of the following values (colon is optional, no spaces needed) to sort the dir command result in the specified manner:

d = sort by date/time (oldest first)

e = sort by extension (alphabetical)

g = group directory first, followed by files

n = sort by name (alphabetical)

s = sort by size (smallest first)

= Use this as a prefix with any of the above values to reverse the order (-d to sort by newest first, -s for largest first, etc.).

/p This option displays the results one page at a time, interrupted with a Press any key to continue… prompt. Using /p is very similar to using the dir command with the more command.
/q Use this switch to display the owner of the file or folder in the results. The easiest way to view or change a file’s ownership from within Windows is via the Advanced button in the Security tab when looking at the file’s Properties.
/r The /r option shows any alternate data streams (ADS) that are part of a file. The data stream itself is listed in a new row, under the file, and is always suffixed with $DATA, making them easy to spot.
/s This option shows all the files and folders in the specified directory plus all of the files and folders contained within any subdirectories of that specified directory.
/t

Use this option with one of the values below (colon is optional, no spaces needed) to specify a time field to be used when sorting and/or displaying results:

a = last access

c = created

w = last written

/w Use /w to show results in «wide format» which limits the items displayed to just folders (contained within brackets) and file names with their extensions. Items are listed left-to-right and then down rows. Standard dir command header and footer data remain the same.
/x This switch shows the «short name» equivalent for files whose long names don’t comply with non-8dot3 rules.
/4 The /4 switch forces the use of 4-digit years. At least in newer versions of Windows, the 4-digit year display is the default behavior and /-4 doesn’t result in a 2-digit year display.
/? Use the help switch with the dir command to show details about the above options directly in the Command Prompt window. Executing dir /? is the same as using the help command to execute help dir.

Dir Command Examples

Below are some of the different ways you can use the dir command:

Run Without Switches

dir

In this example, the dir command is used alone, without any drive:, path, filename specifications, nor any switches, producing a result like this:

C:\>dir
Volume in drive C has no label.
Volume Serial Number is F4AC-9851
Directory of C:\
09/02/2015 12:41 PM 
$SysReset
05/30/2016 06:22 PM 93 HaxLogs.txt
05/07/2016 02:58 AM PerfLogs
05/22/2016 07:55 PM Program Files
05/31/2016 11:30 AM Program Files (x86)
07/30/2015 04:32 PM Temp
05/22/2016 07:55 PM Users
05/22/2016 08:00 PM Windows
05/22/2016 09:50 PM Windows.old
1 File(s) 93 bytes

As you can see, the dir command was executed from the root directory of C (i.e., C:\>). Without specifying where exactly to list the folder and file contents from, the command defaults to displaying this information from where the command was executed.

List Hidden Items

dir c:\users /ah

In the above example, we’re requesting that the dir command show results from the drive: and path of c:\users, not from the location we’re running the command from. We’re also specifying, via the /a switch with the h attribute, that we’d like to only see hidden items, resulting in something like this:

C:\>dir c:\users /ah
Volume in drive C has no label.
Volume Serial Number is F4AC-9851
Directory of c:\users
05/07/2016 04:04 AM All Users [C:\ProgramData]
05/22/2016 08:01 PM 
Default
05/07/2016 04:04 AM Default User [C:\Users\Default]
05/07/2016 02:50 AM 174 desktop.ini
1 File(s) 174 bytes

The small list of directories and the single file you see in the result above doesn’t make up the entirety of the c:\users folder—just the hidden files and folders. To see all files and folders, you would execute dir c:\users /a (removing the h) instead.

Search for File In Any Folder

dir c:\*.csv /s /b > c:\users\tim\desktop\csvfiles.txt

In this slightly more complex, but much more practical, example for the dir command, we’re requesting that our entire hard drive be searched for CSV files and then the bare minimum results are outputted to a text document. Let’s look at this piece by piece:

  • c:\*.csv tells the dir command to look at all files (*) that end in the CSV (.csv) extension in the root of the c: drive.
  • /s instructs it to go deeper than the root of c: and instead, search for files like this in every folder, as deep as the folders go.
  • /b removes anything but the path and file name, essentially creating a readable «list» of these files.
  • > is a redirection operator, meaning «send to» somewhere.
  • c:\users\tim\desktop\csvfiles.txt is the destination for the > redirector, meaning that results will be written to the csvfiles.txt file instead of in Command Prompt, which will be created at the c:\users\tim\desktop location (i.e., the Desktop you see when you’re logged in).

When you redirect command output to a file, as we did here in this dir command example, Command Prompt doesn’t display anything. However, the exact output you would have seen is instead located inside that text file. Here’s what our csvfiles.txt looked like after the dir command had completed:

c:\ProgramData\Intuit\Quicken\Inet\merchant_alias.csv
c:\ProgramData\Intuit\Quicken\Inet\merchant_common.csv
c:\Users\All Users\Intuit\Quicken\Inet\merchant_alias.csv
c:\Users\All Users\Intuit\Quicken\Inet\merchant_common.csv
c:\Users\Tim\AppData\Roaming\condition.2.csv
c:\Users\Tim\AppData\Roaming\line.csv
c:\Users\Tim\AppData\Roaming\media.csv

While you certainly could have skipped the file redirection, and even the «bare format» switch, the results would have been very difficult to work within the Command Prompt window, making it hard to get to what you were after.

Related Commands

The dir command is often used with the del command. After using dir to find the name and location of the file(s) in any particular folder(s), del can be used to delete files directly from the Command Prompt.

Similar is the rmdir /s command, and older deltree command, used to delete folders and files. The rmdir command (without the /s option) is useful for deleting empty folders that you find with the dir command.

As mentioned above, the dir command is also often used with a redirection operator.

Thanks for letting us know!

Get the Latest Tech News Delivered Every Day

Subscribe

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:\Windows\System32 directory:

dir C:\Windows\System32

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

dir C:\Windows\System32\*.txt

Search for files with .dll extension in C:\Windows\System32 and all subdirectories:

dir /s C:\Windows\System32\*.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.

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

  • Команда config в командной строке windows 10
  • Коллекции иконок для windows 10
  • Команда check disk windows 10
  • Количество ядер при загрузке windows 10
  • Команда bootrec для windows 10