Chkdsk
Checks the file system and file system metadata of a volume for logical and physical errors. If used without parameters, chkdsk displays only the status of the volume and does not fix any errors. If used with the /f, /r, /x, or /b parameters, it fixes errors on the volume.
Membership in the local Administrators group, or equivalent, is the minimum required to run chkdsk . To open a command prompt window as an administrator, right-click Command prompt in the Start menu, and then click Run as administrator .
Interrupting chkdsk is not recommended. However, canceling or interrupting chkdsk should not leave the volume any more corrupt than it was before chkdsk was run. Rerunning chkdsk checks and repairs any remaining corruption on the volume.
For examples of how to use this command, see Examples.
Syntax
chkdsk [[[]]] [/f] [/v] [/r] [/x] [/i] [/c] [/l[:]] [/b]
Parameters
Parameter | Description |
---|---|
Specifies the drive letter (followed by a colon), mount point, or volume name. | |
[] | Use with file allocation table (FAT) and FAT32 only. Specifies the location and name of a file or set of files that you want chkdsk to check for fragmentation. You can use the ? and * wildcard characters to specify multiple files. |
/f | Fixes errors on the disk. The disk must be locked. If chkdsk cannot lock the drive, a message appears that asks you if you want to check the drive the next time you restart the computer. |
/v | Displays the name of each file in every directory as the disk is checked. |
/r | Locates bad sectors and recovers readable information. The disk must be locked. /r includes the functionality of /f, with the additional analysis of physical disk errors. |
/x | Forces the volume to dismount first, if necessary. All open handles to the drive are invalidated. /x also includes the functionality of /f. |
/i | Use with NTFS only. Performs a less vigorous check of index entries, which reduces the amount of time required to run chkdsk. |
/c | Use with NTFS only. Does not check cycles within the folder structure, which reduces the amount of time required to run chkdsk. |
/l[:] | Use with NTFS only. Changes the log file size to the size you type. If you omit the size parameter, /l displays the current size. |
/b | NTFS only: Clears the list of bad clusters on the volume and rescans all allocated and free clusters for errors. /b includes the functionality of /r. Use this parameter after imaging a volume to a new hard disk drive. |
/? | Displays help at the command prompt. |
Remarks
- Skipping volume checks The /i or /c switch reduces the amount of time required to run chkdsk by skipping certain volume checks.
- Checking a locked drive at restart If you want chkdsk to correct disk errors, you cannot have open files on the drive. If files are open, the following error message appears:
Chkdsk cannot run because the volume is in use by another process. Would you like to schedule this volume to be checked the next time the system restarts? (Y/N)
10 lost allocation units found in 3 chains. Convert lost chains to files?
Examples
If you want to check the disk in drive D and have Windows fix errors, type:
chkdsk d: /f
If it encounters errors, chkdsk pauses and displays messages. Chkdsk finishes by displaying a report that lists the status of the disk. You cannot open any files on the specified drive until chkdsk finishes.
To check all files on a FAT disk in the current directory for noncontiguous blocks, type:
chkdsk *.*
Chkdsk displays a status report, and then lists the files that match the file specifications that have noncontiguous blocks.
chkdsk
Checks the file system and file system metadata of a volume for logical and physical errors. If used without parameters, chkdsk displays only the status of the volume and does not fix any errors. If used with the /f, /r, /x, or /b parameters, it fixes errors on the volume.
Membership in the local Administrators group, or equivalent, is the minimum required to run chkdsk. To open a command prompt window as an administrator, right-click Command prompt in the Start menu, and then click Run as administrator.
Interrupting chkdsk is not recommended. However, canceling or interrupting chkdsk should not leave the volume any more corrupt than it was before chkdsk was run. Running chkdsk again checks and should repair any remaining corruption on the volume.
Chkdsk can be used only for local disks. The command cannot be used with a local drive letter that has been redirected over the network.
Syntax
chkdsk [[[]]] [/f] [/v] [/r] [/x] [/i] [/c] [/l[:]] [/b]
Parameters
Parameter | Description |
---|---|
Specifies the drive letter (followed by a colon), mount point, or volume name. | |
[ [] | Use with file allocation table (FAT) and FAT32 only. Specifies the location and name of a file or set of files that you want chkdsk to check for fragmentation. You can use the ? and * wildcard characters to specify multiple files. |
/f | Fixes errors on the disk. The disk must be locked. If chkdsk cannot lock the drive, a message appears that asks you if you want to check the drive the next time you restart the computer. |
/v | Displays the name of each file in every directory as the disk is checked. |
/r | Locates bad sectors and recovers readable information. The disk must be locked. /r includes the functionality of /f, with the additional analysis of physical disk errors. |
/x | Forces the volume to dismount first, if necessary. All open handles to the drive are invalidated. /x also includes the functionality of /f. |
/i | Use with NTFS only. Performs a less vigorous check of index entries, which reduces the amount of time required to run chkdsk. |
/c | Use with NTFS only. Does not check cycles within the folder structure, which reduces the amount of time required to run chkdsk. |
/l[: ] | Use with NTFS only. Changes the log file size to the size you type. If you omit the size parameter, /l displays the current size. |
/b | Use with NTFS only. Clears the list of bad clusters on the volume and rescans all allocated and free clusters for errors. /b includes the functionality of /r. Use this parameter after imaging a volume to a new hard disk drive. |
/scan | Use with NTFS only. Runs an online scan on the volume. |
/forceofflinefix | Use with NTFS only (must be used with /scan). Bypass all online repair; all defects found are queued for offline repair (for example, chkdsk /spotfix ). |
/perf | Use with NTFS only (must be used with /scan). Uses more system resources to complete a scan as fast as possible. This may have a negative performance impact on other tasks running on the system. |
/spotfix | Use with NTFS only. Runs spot fixing on the volume. |
/sdcleanup | Use with NTFS only. Garbage collect unneeded security descriptor data (implies /f). |
/offlinescanandfix | Runs an offline scan and fix on the volume. |
/freeorphanedchains | Use with FAT/FAT32/exFAT only. Frees any orphaned cluster chains instead of recovering their contents. |
/markclean | Use with FAT/FAT32/exFAT only. Marks the volume clean if no corruption was detected, even if /f was not specified. |
/? | Displays help at the command prompt. |
Remarks
- The /i or /c switch reduces the amount of time required to run chkdsk by skipping certain volume checks.
- If you want chkdsk to correct disk errors, you can’t have open files on the drive. If files are open, the following error message appears:
Chkdsk cannot run because the volume is in use by another process. Would you like to schedule this volume to be checked the next time the system restarts? (Y/N)
10 lost allocation units found in 3 chains. Convert lost chains to files?
- If you press Y, Windows saves each lost chain in the root directory as a file with a name in the format File .chk. When chkdsk finishes, you can check these files to see if they contain any data you need.
- If you press N, Windows fixes the disk, but it does not save the contents of the lost allocation units.
Understanding exit codes
The following table lists the exit codes that chkdsk reports after it has finished.
Exit code | Description |
---|---|
0 | No errors were found. |
1 | Errors were found and fixed. |
2 | Performed disk cleanup (such as garbage collection) or did not perform cleanup because /f was not specified. |
3 | Could not check the disk, errors could not be fixed, or errors were not fixed because /f was not specified. |
Examples
To check the disk in drive D and have Windows fix errors, type:
chkdsk d: /f
If it encounters errors, chkdsk pauses and displays messages. Chkdsk finishes by displaying a report that lists the status of the disk. You cannot open any files on the specified drive until chkdsk finishes.
To check all files on a FAT disk in the current directory for noncontiguous blocks, type:
chkdsk *.*
Chkdsk displays a status report, and then lists the files that match the file specifications that have noncontiguous blocks.
Viewing chkdsk logs
There are two methods that can be used to retrieve chkdsk log file(s) in Windows. View the methods described below:
To view logs with Event Viewer, navigate to the following:
- Start >Control Panel >Administrative Tools >Event Viewer. Alternatively, press Win + R keys to bring up the run dialog box, type eventvwr.msc, and select OK.
- Expand Windows Logs > right-click on Application > select Filter Current Log.
- Within the Filter Current Log window, navigate to Event sources drop-down menu, select Chkdsk and Wininit.
- Click OK to finish filtering for these two sources.
There are two source types when retrieving logs in PowerShell, chkdsk and wininit. Run one of the two commands in PowerShell to view the most current chkdsk log:
get-winevent -FilterHashTable @ | ? | fl timecreated, message
get-winevent -FilterHashTable @ | ? | fl timecreated, message
To export the log to a specific location, the following can be added to the end of the command | out-file «$env:userprofile\location\filename.txt» . Example:
get-winevent -FilterHashTable @ | ? | fl timecreated, message | out-file "C:\Users\Administrator\Desktop\Chkdsk_Log.txt"
get-winevent -FilterHashTable @ | ? | fl timecreated, message | out-file "C:\Users\Administrator\Desktop\Wininit_Log.txt"
Related links
chkdsk
Проверяет файловую систему и метаданные файловой системы тома на наличие логических и физических ошибок. При использовании без параметров chkdsk отображает только состояние тома и не исправляет никаких ошибок. При использовании с параметрами /f, /r, /x или /b он исправляет ошибки на томе.
Для запуска chkdsk требуется членство в локальной группе администраторов или аналогичной группе. Чтобы открыть окно командной строки от имени администратора, щелкните правой кнопкой мыши Командная строка в меню Пуск и выберите команду Запуск от имени администратора.
Прерывание chkdsk не рекомендуется. Однако при отмене или прерывании chkdsk не следует оставлять том более поврежденным, чем до запуска chkdsk . Запуск chkdsk снова проверяет и должен исправить все оставшиеся повреждения тома.
Chkdsk можно использовать только для локальных дисков. Команду нельзя использовать с буквой локального диска, которая была перенаправлена по сети.
Синтаксис
chkdsk [[[]]] [/f] [/v] [/r] [/x] [/i] [/c] [/l[:]] [/b]
Параметры
Параметр | Описание |
---|---|
Указывает букву диска (за которой следует двоеточие), точку подключения или имя тома. | |
[ [] | Используйте только с таблицей выделения файлов (FAT) и FAT32. Указывает расположение и имя файла или набора файлов, которые chkdsk будет проверять на фрагментацию. Для указания нескольких файлов можно использовать подстановочные знаки ? и * . |
/f | Исправляет ошибки на диске. Диск должен быть заблокирован. Если chkdsk не может заблокировать диск, появится сообщение с запросом на проверку диска при следующей перезагрузке компьютера. |
/v | Отображает имя каждого файла в каждом каталоге при проверке диска. |
/r | Находит поврежденные секторы и восстанавливает удобочитаемую информацию. Диск должен быть заблокирован. /r включает функции /f с дополнительным анализом ошибок физического диска. |
/x | При необходимости принудительно отключит том. Все открытые дескрипторы диска становятся недействительными. /x также включает функции /f. |
/i | Используйте только с NTFS. Выполняет менее энергичную проверку записей индекса, что сокращает время, необходимое для выполнения chkdsk. |
/C | Используйте только с NTFS. Не проверяет циклы в структуре папок, что сокращает время, необходимое для выполнения chkdsk. |
/l[: ] | Используйте только с NTFS. Изменяет размер файла журнала на размер, который вы вводите. Если опустить параметр size, параметр /l отображает текущий размер. |
/b | Используйте только с NTFS. Очищает список недопустимых кластеров на томе и повторно сканирует все выделенные и свободные кластеры на наличие ошибок. /b включает функции /r. Используйте этот параметр после создания образа тома на новом жестком диске. |
/Сканирования | Используйте только с NTFS. Выполняет проверку тома в сети. |
/forceofflinefix | Используйте только с NTFS (необходимо использовать с параметром /scan). Обход всех сетевых исправлений; Все обнаруженные дефекты помещаются в очередь для восстановления в автономном режиме (например, chkdsk /spotfix ). |
/Перфорация | Используйте только с NTFS (необходимо использовать с параметром /scan). Использует больше системных ресурсов для максимально быстрого завершения сканирования. Это может отрицательно сказаться на производительности других задач, выполняемых в системе. |
/spotfix | Используйте только с NTFS. Выполняет точечное исправление на томе. |
/sdcleanup | Используйте только с NTFS. Мусор собирает ненужные данные дескриптора безопасности (подразумевает /f). |
/offlinescanandfix | Выполняет автономную проверку и исправление на томе. |
/freeorphanedchains | Используйте только с FAT,FAT32/exFAT. Освобождает все потерянные цепочки кластера вместо восстановления их содержимого. |
/markclean | Используйте только с FAT,FAT32/exFAT. Помечает том чистым, если повреждения не обнаружены, даже если параметр /f не был указан. |
/? | Отображение справки в командной строке. |
Комментарии
- Параметр /i или /c сокращает время, необходимое для выполнения chkdsk , пропуская определенные проверки тома.
- Если вы хотите, чтобы chkdsk исправлял ошибки диска, вы не можете иметь открытые файлы на диске. Если файлы открыты, появляется следующее сообщение об ошибке:
Chkdsk cannot run because the volume is in use by another process. Would you like to schedule this volume to be checked the next time the system restarts? (Y/N)
10 lost allocation units found in 3 chains. Convert lost chains to files?
- Если нажать клавишу Y, Windows сохраняет каждую потерянную цепочку в корневом каталоге в виде файла с именем в формате File.chk . Когда chkdsk завершит работу, вы можете проверить эти файлы, чтобы узнать, содержат ли они какие-либо необходимые данные.
- Если нажать клавишу N, Windows исправит диск, но не сохранит содержимое потерянных единиц выделения.
Основные сведения о кодах выхода
В следующей таблице перечислены коды выхода, которые chkdsk сообщает после завершения.
Код выхода | Описание |
---|---|
0 | Ошибки не найдены. |
1 | Обнаружены и исправлены ошибки. |
2 | Выполнил очистку диска (например, сборку мусора) или не выполнил очистку, так как параметр /f не указан. |
3 | Не удалось проверить диск, ошибки не удалось исправить или ошибки не были исправлены, так как параметр /f не был указан. |
Примеры
Чтобы проверить диск на диске D и устранить ошибки Windows, введите следующую команду:
chkdsk d: /f
Если возникают ошибки, chkdsk приостанавливается и отображает сообщения. Chkdsk завершается отображением отчета со списком состояния диска. Вы не сможете открыть файлы на указанном диске, пока не завершится chkdsk .
Чтобы проверить все файлы на диске FAT в текущем каталоге на наличие несмежных блоков, введите:
chkdsk *.*
Chkdsk отображает отчет о состоянии, а затем выводит список файлов, соответствующих спецификациям файлов с несмежными блоками.
Просмотр журналов chkdsk
Существует два метода, которые можно использовать для получения файлов журнала chkdsk в Windows. Просмотрите описанные ниже методы.
Чтобы просмотреть журналы с Просмотр событий, перейдите к следующему:
- Запустите >панель управления>Административные средства>Просмотр событий. Кроме того, можно нажать клавиши WIN+R , чтобы открыть диалоговое окно запуска, введите eventvwr.msc и нажмите кнопку ОК.
- Разверните узел Журналы> Windows, щелкните правой кнопкой мыши приложение> , выберите Фильтр текущего журнала.
- В окне Фильтрация текущего журнала перейдите в раскрывающееся меню Источники событий и выберите Chkdsk и Wininit.
- Нажмите кнопку ОК , чтобы завершить фильтрацию для этих двух источников.
Существует два типа источника при получении журналов в PowerShell: chkdsk и wininit. Выполните одну из двух команд в PowerShell, чтобы просмотреть актуальный журнал chkdsk:
get-winevent -FilterHashTable @ | ? | fl timecreated, message
get-winevent -FilterHashTable @ | ? | fl timecreated, message
Чтобы экспортировать журнал в определенное расположение, в конец команды | out-file «$env:userprofile\location\filename.txt» можно добавить следующее: Пример
get-winevent -FilterHashTable @ | ? | fl timecreated, message | out-file "C:\Users\Administrator\Desktop\Chkdsk_Log.txt"
get-winevent -FilterHashTable @ | ? | fl timecreated, message | out-file "C:\Users\Administrator\Desktop\Wininit_Log.txt"
Связанные ссылки
При подготовке материала использовались источники:
https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-r2-and-2012/cc730714(v=ws.11)
https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/chkdsk
https://learn.microsoft.com/ru-ru/windows-server/administration/windows-commands/chkdsk