Для проверки целостности системных файлов и восстановления поврежденных файлов (библиотек) компонентов в Windows (Windows Server) можно использовать команды SFC и DISM. Эти две утилиты могут быть крайне полезными, если операционная система Windows работает нестабильно, появляются ошибки при запуске стандартных приложений или служб, после вирусного заражения и т.д.
В этой статье мы рассмотрим, как использовать команды
sfc /scannow
,
DISM /Online /Cleanup-Image /RestoreHealth
или
Repair-WindowsImage -Online -RestoreHealth
для восстановления образа и системных фалов в Windows 10/11 и Windows Server 2022/2019/2016.
Содержание:
- SFC /scannow: восстановление системных файлов Windows
- Проверка целостности хранилища компонентов Windows с помощью DISM
- Восстановление образа Windows с помощью DISM /RestoreHealth
- DISM /Source: восстановление образа Windows с установочного диска
- Восстановление образа Windows с помощью PowerShell
- DISM: восстановление поврежденного хранилища компонентов, если Windows не загружается
SFC /scannow: восстановление системных файлов Windows
Перед тем, как восстанавливать образ Windows с помощью DISM, рекомендуется сначала попробовать проверить целостность системных файлов с помощью утилиты SFC (System File Checker). Команда
sfc /scannow
позволяет проверить целостность системных файлов Windows. Если какие-то системные файлы отсутствуют или повреждены, утилита SFC попробует восстановить их оригинальные копии из хранилища системных компонентов Windows (каталог C:\Windows\WinSxS).
Утилита SFC записывает все свои действия в лог-файл
windir%\logs\cbs\cbs.log
. Для всех записей, оставленных SFC в файле CBS.log проставлен тег [SR]. Чтобы выбрать из лога только записи, относящиеся к SFC, выполните команду:
findstr /c:"[SR]" %windir%\Logs\CBS\CBS.log >"%userprofile%\Desktop\sfc.txt"
Если команда sfc /scannow возвращает ошибку “
Программа защиты ресурсов Windows обнаружила повреждённые файлы, но не может восстановить некоторые из них / Windows Resource Protection found corrupt files but was unable to fix some of them
”, скорее всего утилита не смогла получить необходимые файла из хранилища компонентов (образа) Windows.
В этом случае вам нужно попробовать восстановить хранилище компонентов вашего образа Windows с помощью DISM.
После восстановления образа вы можете повторно использовать утилиту SFC для восстановления системных файлов.
Проверка целостности хранилища компонентов Windows с помощью DISM
Утилита DISM (Deployment Image Servicing and Management) доступна во всех версиях Windows, начиная с Vista.
Для сканирования образа Windows на наличие ошибок и их исправления используется параметр DISM /Cleanup-image. Команды DISM нужно запускать из командной строки, с правами администратора.
Чтобы проверить наличие признака повреждения хранилища компонентов в образе Windows (флаг CBS), выполните команду (не применимо к Windows 7/Server 2008R2):
DISM /Online /Cleanup-Image /CheckHealth
Эта команда не выполняет полное сканирование хранилища компонентов. Проверяются лишь записанные ранее маркеры повреждений и события в журнале Windows. Изменения в образ не вносятся. Команда проверит, не помечен ли ваш образ Windows как поврежденный и возможно ли исправить его.
В этом примере команда вернула, что с образом все хорошо:
No component store corruption detected. The operation completed successfully.
Чтобы выполнить полное сканирование хранилища компонентов на наличие повреждений в хранилище компонентов Windows, запустите команду:
DISM /Online /Cleanup-Image /ScanHealth
Команда проверки образа Windows может выполняться довольно долго (от 10 до 30 минут). И вернет один из трех результатов:
- No component store corruption detected – DISM не обнаружил повреждения в хранилище компонентов;
- The component store is repairable – DISM обнаружил ошибки в хранилище компонентов и может исправить их;
- The component store is not repairable – DISM не может исправить хранилище компонентов Windows (попробуйте использовать более новую версию DISM или вам придется восстанавливать образ Windows из резервной копии, сбрасывать или полностью переустанавливать вашу копию Windows.
В Windows 7 и Windows Server 2008 R2 для использования параметра DISM /ScanHealth нужно установить отдельное обновление KB2966583. Иначе при запуске DISM будет появляться “
Ошибка 87. Параметр ScanHealth не распознан в этом контексте
”.
Команда DISM /ScanHealth может вернуть ошибки:
- Ошибка: 1726. Сбой при удалённом вызове процедуры;
- Ошибка: 1910. Не найден указанный источник экспорта объекта.
Это однозначно говорит о том, что ваш образ Windows поврежден и его нужно восстановить.
Восстановление образа Windows с помощью DISM /RestoreHealth
Чтобы исправить повреждения в хранилище компонентов образа Windows нужно использовать опцию RestoreHealth команды DISM. Эта опция позволит исправить найденные в образе ошибки, автоматически скачать и заменить файлы повреждённых или отсутствующих компонентов эталонными версиями файлов из центра обновлений Windows (на компьютере должен быть доступ в Интернет). Выполните команду:
DISM /Online /Cleanup-Image /RestoreHealth
В Windows 7/2008 R2 эта команда выглядит по другому:
DISM.exe /Online /Cleanup-Image /ScanHealth
Процесс сканирования и восстановления компонентов может быть довольно длительным (30 минут или более). DISM автоматически загрузит недостающие или поврежденные файлы образа с серверов Windows Update.
Восстановление выполнено успешно. Операция успешно завершена.
The restore operation completed successfully.
DISM /Source: восстановление образа Windows с установочного диска
Если на компьютере (сервере) отсутствует доступ в Интернет или отключена/повреждена служба Windows Update (как восстановить клиент Windows Update), то при восстановлении хранилища компонентов появятся ошибки:
- 0x800f0906 — Не удалось скачать исходные файлы. Укажите расположение файлов, необходимых для восстановления компонента, с помощью параметра Источник (0x800f0906 — The source files could not be downloaded. Use the source option to specify the location of the files that are required to restore the feature);
- Ошибка: 0x800f0950 — Сбой DISM. Операция не выполнена (0x800f0950 — DISM failed. No operation was performed);
- Ошибка:0x800F081F. Не удалось найти исходные файлы. Укажите расположение файлов, необходимых для восстановления компонента, с помощью параметра Источник (Error 0x800f081f, The source files could not be found. Use the «Source» option to specify the location of the files that are required to restore the feature).
<
Во всех этих случаях вы можете использовать альтернативные средства получения оригинальных файлов хранилища компонентов. Это может быть:
- Установочный диск/флешка/iso образ Windows
- Смонтированный файл wim
- Папка \sources\SxS с установочного диска
- Файл install.wim с установочным образом Windows
Вы можете указать WIM или ESD файл с оригинальным установочным образом Windows, который нужно использовать в качестве источника для восстановления файлов системы. Предположим, вы смонтировали установочный ISO образ Windows 11 в виртуальный привод D:.
Примечание. Для восстановления поврежденных файлов в хранилище компонентов из локального источника версия и редакция Windows в образе должна полностью совпадать с вашей.
С помощью следующей PowerShell команды проверьте, какая версия Windows установлена на вашем компьютере:
Get-ComputerInfo |select WindowsProductName,WindowsEditionId,WindowsVersion, OSDisplayVersion
Выведите список доступных версий Windows в установочном образе:
Get-WindowsImage -ImagePath "D:\sources\install.wim"
В нашем случае образ Windows 11 Pro в образе install.wim имеет
ImageIndex = 6
.
Для восстановления хранилища компонентов из локального WIM/ESD файла с блокированием доступа в интернет, выполните следующую команду (не забудьте указать ваш индекс версии Windows в файле):
DISM /online /cleanup-image /restorehealth /source:WIM:D:\sources\install.wim:6 /limitaccess
Или:
DISM /online /cleanup-image /restorehealth /source:ESD:D:\sources\install.esd:6 /limitaccess
Если при запуске появляется
- Ошибка Error: 50: DISM does not support servicing Windows PE with the /Online option, значит ваша DISM считает, что вы используете WinPE образWindows. Чтобы исправить это, удалите ветку реестра HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\MiniNT.
Ошибка DISM Error 87: проверьте правильно написания команды, убедитесь что вы используете версию DISM для вашей версии Windows (обычно бывает при загрузке через WinPE/WinRE).
Утилита DISM пишет подробный журнал сканирования и восстановления системных файлов в файл
C:\Windows\Logs\DISM\dism.log
.
После восстановления хранилища компонентов вы можете запустить утилиту проверки системных файлов
sfc /scannow
. Скорее всего она успешно восстановит поврежденные файлы:
Программа защиты ресурсов Windows обнаружила поврежденные файлы и успешно их восстановила.
Windows Resource Protection found corrupt files and successfully repaired them.
Если все системные файлы целы, появится сообщение:
Windows Resource Protection did not find any integrity violations
Восстановление образа Windows с помощью PowerShell
В версии PowerShell в Windows 10/11 и Windows Server 2022/2019 есть аналоги рассмотренных выше команд DISM. Для сканирования хранилища компонентов и поиска повреждений в образе выполните:
Repair-WindowsImage -Online –ScanHealth
Если ошибок в хранилище компонентов не обнаружено, появится сообщение:
ImageHealth State: Healthy
Для запуска восстановления системных компонентов и файлов наберите:
Repair-WindowsImage -Online -RestoreHealth
При отсутствии доступа к интернету эта команда может зависнуть в процессе восстановления образа. Вы можете восстановить системные компоненты из локальной копии образа Windows в виде WIM/ESD файла, скопированного с установочного ISO образа Windows 10 (здесь также нужно указать индекс версии Windows в wim файле в качестве источника восстановления):
Repair-WindowsImage -Online -RestoreHealth -Source D:\sources\install.wim:5 –LimitAccess
DISM: восстановление поврежденного хранилища компонентов, если Windows не загружается
Если Windows не загружается корректно, вы можете выполнить проверку и исправление системных файлов в оффлайн режиме.
- Для этого загрузите компьютер с установочного образа Windows (проще всего создать загрузочную USB флешку с Windows 10/11 с помощью Media Creation Tool) и на экране начала установки нажмите
Shift + F10
- Чтобы разобраться с буквами дисков, назначенных в среде WinPE, выполните команду
diskpart
->
list vol
(в моем примере диску, на котором установлена Windows присвоена буква C:\, эту букву я буду использовать в следующих командах); - Проверим системные файлы и исправим поврежденные файлы командой:
sfc /scannow /offbootdir=C:\ /offwindir=C:\Windows
- Для исправления хранилища компонентов используйте следующую команду (в качестве источника для восстановления компонентов мы используем WIM файл с установочным образом Windows 10, с которого мы загрузили компьютер):
Dism /image:C:\ /Cleanup-Image /RestoreHealth /Source:WIM:D:\sources\install.wim:6
- Если на целевом диске недостаточно места, то для извлечения временных файлов нам понадобится отдельный диск достаточного размера, например F:\, на котором нужно создать пустой каталог:
mkdir f:\scratch
и запустить восстановление хранилища компонентов командой:
Dism /image:C:\ /Cleanup-Image /RestoreHealth /Source:D:\sources\install.wim /ScratchDir:F:\scratch
Совет. Другие полезные команды DISM, которые должен знать администратор:
-
DISM /Add-Package
– установка MSU/CAB файлов обновлений, интеграция обновлений в образ Windows; -
DISM /Get-Drivers
– получение списка установленных драйверов; -
DISM /Add-Driver
– добавление драйверов в образ; -
DISM /Export-Driver
– экспорт установленных драйверов Windows; -
DISM /Add-Capability
– установка дополнительных компонентов Windows через Features on Demand (например, RSAT, сервер OpenSSH или ssh клиент Windows; -
DISM /Enable-Features
и
/Disable-Features
– включение и отключение компонентов Windows (например, протокола SMBv1), -
DISM /online /Cleanup-Image /StartComponentCleanup
– очистка хранилища компонентов и удаление старых версий компонентов (папки WinSxS); -
DISM /set-edition
– конвертирование ознакомительной редакции Windows на полную без переустановки.
Provide feedback
Saved searches
Use saved searches to filter your results more quickly
Sign up
Appearance settings
Administrators can diagnose and treat a buggy server operating system by using the Windows SFC and DISM utilities for image analysis and repairs.
Over time, system files in a Windows Server installation might require a fix. You can often repair the operating system without taking the server down by using Windows SFC or the more robust and powerful Deployment Image Servicing and Management commands.
Windows System File Checker (SFC) and Deployment Image Servicing and Management (DISM) are administrative utilities that can alter system files, so they must be run in an administrator command prompt window.
Start with Windows SFC
The Windows SFC utility scans and verifies version information, file signatures and checksums for all protected system files on Windows desktop and server systems. If the command discovers missing protected files or alterations to existing ones, Windows SFC will attempt to replace the altered files with a pristine version from the %systemroot%\system32\dllcache folder.
The system logs all activities of the Windows SFC command to the %Windir%\CBS\CBS.log file. If the tool reports any nonrepairable errors, then you’ll want to investigate further. Search for the word corrupt to find most problems.
Windows SFC command syntax
Open a command prompt with administrator rights and run the following command to start the file checking process:
C:\Windows\System32>sfc /scannow
The /scannow parameter instructs the command to run immediately. It can take some time to complete — up to 15 minutes on servers with large data drives is not unusual — and usually consumes 60%-80% of a single CPU for the duration of its execution. On servers with more than four cores, it will have a slight impact on performance.
There are times Windows SFC cannot replace altered files. This does not always indicate trouble. For example, recent Windows builds have included graphics driver data that was reported as corrupt, but the problem is with Windows file data, not the files themselves, so no repairs are needed.
If Windows SFC can’t fix it, try DISM
The DISM command is more powerful and capable than Windows SFC. It also checks a different file repository — the %windir%\WinSXS folder, aka the «component store» — and is able to obtain replacement files from a variety of potential sources. Better yet, the command offers a quick way to check an image before attempting to diagnose or repair problems with that image.
Run DISM with the following parameters:
C:\Windows\System32>dism /Online /Cleanup-Image /CheckHealth
Even on a server with a huge system volume, this command usually completes in less than 30 seconds and does not tax system resources. Unless it finds some kind of issue, the command reports back «No component store corruption detected.» If the command finds a problem, this version of DISM reports only that corruption was detected, but no supporting details.
Corruption detected? Try ScanHealth next
If DISM finds a problem, then run the following command:
C:\Windows\System32>dism /Online /Cleanup-Image /ScanHealth
This more elaborate version of the DISM image check will report on component store corruption and indicate if repairs can be made.
If corruption is found and it can be repaired, it’s time to fire up the /RestoreHealth directive, which can also work from the /online image, or from a different targeted /source.
Run the following commands using the /RestoreHealth parameter to replace corrupt component store entries:
C:\Windows\System32>dism /Online /Cleanup-Image /RestoreHealth
C:\Windows\System32>dism /source:<spec> /Cleanup-Image /RestoreHealth
You can drive file replacement from the running online image easily with the same syntax as the preceding commands. But it often happens that local copies aren’t available or are no more correct than the contents of the local component store itself. In that case, use the /source directive to point to a Windows image file — a .wim file or an .esd file — or a known, good, working WinSXS folder from an identically configured machine — or a known good backup of the same machine to try alternative replacements.
By default, the DISM command will also try downloading components from the Microsoft download pages; this can be turned off with the /LimitAccess parameter. For details on the /source directive syntax, the TechNet article «Repair a Windows Image» is invaluable.
DISM is a very capable tool well beyond this basic image repair maneuver. I’ve compared it to a Swiss army knife for maintaining Windows images. Windows system admins will find DISM to be complex and sometimes challenging but well worth exploring.
Next Steps
Rebuild missing SYSVOL in Active Directory
Networking enhancements coming in Windows Server 2016
Manage a library of images for Windows deployment
Dig Deeper on Microsoft messaging and collaboration
-
10 troubleshooting steps for when Windows Update is frozen
By: Robert Sheldon
-
7 steps to fix a black screen in Windows 11
By: Robert Sheldon
-
How to create a custom Windows 11 ISO file
By: Ed Tittel
-
Windows Imaging Format (WIM)
By: Rahul Awati
The system file checker tool is a useful command used to scan and repair corrupt or damaged system files. This command is usually used when users encounter problems with the system files of Windows OS.
sfc /scannow is the most popular command to scan for corrupt system files immediately. It will not only scan, but also try to repair or replace corrupt system files with healthy ones. It requires a Windows installation source to copy files from.
The system file checker is a universal command and can be used in all Windows operating systems, including Windows 11, Windows 10, Windows 8, Windows 7 and Windows Vista.
This command line can perform several functions. We will discuss these in this article.
Table of Contents
SFC Switches
The table below lists all the switches which can be used with the SFC command-line tool, and their functions:
Commands | Function |
sfc /scannow | Scan for issues. If found, replace the file from the DLL cache. |
sfc /scanonce | Will scan only once. |
sfc /scanboot | Will scan the computer at every boot. |
sfc /revert | Revert the scanning functionality to its original (default) state. |
sfc /purgecache | Will remove the Windows File Protection cache and begin a scan over the system files. |
sfc /cachesize=X | Set the cache size of the Windows File Protection to X MBs. |
sfc /? | Display help regarding switches. |
Today, we are only going to be focusing on the “sfc /scannow” cmdlet as it is the one that quickly and effectively fixes your operating system.
Running Basic SFC Scan
The simplest (and most convenient) method to run the system file checker command is by running the following cmdlet in an elevated Command Prompt window:
sfc /scannow
The cmdlet will then perform its job and attempt to repair any protected files that may have been corrupted. However, that is not always the case, and users may encounter different errors from time to time.
Before we discuss these different errors, let us discuss the various outputs of the basic scan and what each of those means.
Outputs of SFC Scan
As you can observe in the image above, the output of the SFC scan states the following:
Windows Resource Protection found corrupted files and successfully repaired them.
It then also states the location of a CBS.log file which contains the details of the performed scan – we’ll get into that a moment later.
Let us now see all the possible outputs of the SFC scan that different users can encounter and what they mean:
Output Statement | Meaning |
Windows Resource Protection did not find any integrity violations. | No missing or corrupted system files were detected, meaning your system’s integrity is intact. |
Windows Resource Protection could not perform the requested operation. | An unknown issue occurred and the scan could not be performed. In this case, you must adopt the alternative methods given below in this post. |
Windows Resource Protection found corrupt files and successfully repaired them. | Missing or corrupted files were found and have been repaired, restoring your system’s integrity. |
Windows Resource Protection found corrupt files but was unable to fix some of them. | Your system’s integrity was compromised, but SFC did not work. In this case, you must adopt alternative methods to fix the issue or replace the files manually using the given guide further down this post. |
Apart from this, there are other possible issues that you may encounter while performing the scan.
Why SFC Scan Failed
You may encounter any one of the following scenarios while performing an SFC scan. The table below lists those scenarios along with their possible solutions.
Note: The methods to perform these solutions are discussed below.
Symptom of Failure | Possible Solution |
Scan stuck at verification | Run the scan in safe mode or replace files manually |
Scan gets frozen at a certain percentage | First run the DISM tool and then run the SFC scan in safe mode. |
Nothing happens when running “sfc /scannow” | Run the DISM tool first and then run the SFC scan in safe mode. |
SFC scan completely stops | Disable Intel Turbo Memory and try rerunning the scan. |
SFC scan cannot fix the problem | First run the DISM tool and then run the SFC scan in safe mode. |
Scan requires administrative privileges | Run the scan from an administrator account with an elevated Command Prompt. |
Before we discuss the different methods to run the SFC scan, bypassing any issues, let us look at the log file generated when an SFC scan is executed.
How to Open SFC CBS.Log File
When you perform an SFC scan, the system automatically generates a log file named “CBS.log.” This file contains information on the scan that was executed, which can help you advanced troubleshoot if you encounter an issue with the SFC tool.
The CBS.Log file is saved at the following location:
C:\Windows\Logs\CBS
You can open this log file using a text editor, such as Notepad, Word, Wordpad, etc.
Follow these steps to open the file:
-
Navigate to the following location using File Explorer:
C:\Windows\Logs\CBS
-
Here, right-click the file “CBS” then click Open with from the context menu.
Select Open With from context menu -
Now select the program you want to open the text file with from the popup and click Ok.
Select program to open with
The log file will then open in the text editor.
Since the CBS.Log file can be lengthy, you can analyze it using the Find function. You can look for keywords in the entire file using the CTRL + F shortcut keys, and then use the following keywords to look for the details on the file that may have been repaired, not repaired, corrupted, etc. Here is a list of the keywords you can use and the respective features you can find.
Keyword | Details |
Repaired | View files that were repaired |
Cannot repair | View files SFC failed to repair – Will need to be replaced manually |
Corrupt | Files that are or were corrupted – Will need to be replaced manually |
By analyzing the CBS.Log file, you can pinpoint the files which SFC could not repair, and then replace those files manually using the guide given down below.
How to Fix SFC /ScanNow Failed
If you are not able to fix your operating system using the basic approach for running the SFC scan, then there is still plenty you can do to mitigate the problem.
Note: The below methods need to be performed using only an administrative account and any commands need to be run using an elevated Command Prompt.
Note: The steps given below need to be performed in a methodical order as given.
-
Scan Hard Drive
To begin, you first need to scan your hard drive for errors or bad sectors using the Check Disk (CHKDSK) utility, since those could prevent the SFC scan from performing a successful repair. Here is how to do it:
-
Open Command Prompt with administrative privileges.
-
Run the following cmdlet:
Chkdsk C: /f /r /x
-
You will be asked to schedule the CHKDSK utility the next time the computer reboots. Enter Y for yes.
Run Check Disk utility -
Now restart your computer. Once it reboots, the Check Disk utility will run and scan your hard drive. This can take a while, in some cases, hours. Let the scan finish and reboot into Windows.
-
-
Enable Built-In Administrator Account
Now enable the built-in Administrator account, which will be needed by following the steps below. Using this account, you will have elevated privileges required to manipulate protected files.
There are several ways to enable the built-in Administrator account on a Windows computer. Click here to learn more about them.
-
Reboot in Safe Mode
Safe Mode is a diagnostic mode that starts Windows in a basic state, loading a limited set of files and drivers. This is intended for troubleshooting Windows problems.
Perform these steps to boot into Safe Mode with Networking – which means you will have access to the internet which is then later required to run the DISM utility.
-
Open the System Configuration applet by typing in msconfig in the Run Command box.
Open System Configuration applet -
Switch to the Boot tab. Here, in the Boot options section, check the box next to “Safe Boot,” and then select the Network radio button under it. Once done, click Apply and Ok.
Boot into safe mode with networking -
In the confirmation dialog box, click Restart.
Confirm rebooting
Your computer will now reboot into Safe Mode.
Learn other methods to boot into Safe Mode.
-
-
Log In From Built-In Administrator Account
Now you must log in to the Administrator account that you enabled earlier. This will allow you to have the privileges to repair missing or corrupted system files.
-
Run DISM Utility
Once you are logged in, you must first run the DISM utility to fix the system image. Fixing the system image will then allow the SFC scan to perform its task without any hindrance.
The DISM tool can be used to prepare, modify, and repair system images. However, you need an active internet connection to download and replace corrupted content from Windows Update, which is why we opted to boot into Safe Mode with internet connectivity.
Follow these steps to run the DISM utility:
-
Launch the Command Prompt with administrative privileges.
-
Now execute the following cmdlets one after the other, allowing each cmdlet sufficient time to complete.
DISM.exe /Online /Cleanup-image /Checkhealth DISM.exe /Online /Cleanup-image /Scanhealth DISM.exe /Online /Cleanup-image /Restorehealth
Run DISM utility
Once this is done successfully, do not close the Command Prompt.
-
-
Run SFC ScanNow
Now all you need to do is run the basic SFC scan in an attempt to repair the operating system and the corrupted files within. Run the following cmdlet in an elevated Command Prompt:
sfc /scannow
SFC scan in Safe Mode
That is it! This method should eliminate any issues you experience while performing the SFC scan in basic mode. Restart the computer once the scan is complete.
However, if you find the SFC utility is still unable to fix missing or corrupted files, there are still several things you can do. To begin, we suggest you analyze the CBS.Log file, as we discussed earlier in this post.
Run Offline SFC ScanNow from WinPE
The offline version of the SFC scan means that you run the scan from the Windows Preinstallation Environment (WinPE). This method can be especially useful if you are unable to boot into Windows.
This process requires a Windows installation device (DVD, bootable USB) that has the same OS version as installed.
Perform the following steps to attempt and repair any missing or corrupted system files using the SFC scan with WinPE.
-
Plugin the bootable device and boot from it.
-
On the first screen, click Next.
Proceed to next -
Now click Repair your computer.
Attempt to repair -
Now select Troubleshoot.
Select Troubleshoot -
Now select Command Prompt.
Open Command Prompt in WinPE -
The Command Prompt will now open in front of you. Paste the following cmdlet to verify the drive letter assigned to the volume where Windows is installed.
bcdedit
Note down the drive letter beneath “Windows Boot Loader” in front of device.
Note down drive letter Note: Since the drive letters assigned in WinPE are not the same as the default drive letters you see when Windows is booted, these can be different for everyone. Therefore, it is important to determine which drive letter is currently assigned to the boot volume.
-
Now use the following cmdlet to run the SFC scan here, while replacing DriveLetter (in 2 places) with the letter of the drive where Windows is installed as noted in the last step:
sfc /scannow /offbootdir=DriveLetter: /offwindir=DriveLetter:\Windows
-
Once the scan is complete, restart your computer and boot normally into Windows.
If this does not work for you either, you can manually replace the corrupted files yourself.
Manually Replace Corrupted Files
At this point, you must have already analyzed the VBS.Log file we had discussed earlier. Using the file names determined from there, you can manually replace them with healthy files obtained from another computer. Here is how to do it:
-
Start by taking ownership of the corrupted system file. To do so, run the following cmdlet in an elevated Command Prompt while replacing Path&FileName with the complete path and file name of the corrupted file:
takeown /f Path&FileName
Take ownership of file -
Next, grant the Administrators group full access to the file using the following cmdlet while replacing Path&FileName as earlier:
icacls Path&FileName /GRANT ADMINISTRATORS:F
Grant Administrators full rights to file -
Now you should be able to easily replace the file with another copy. At this point, copy the same file from a healthy computer having the same Windows version and paste it here, replacing the current one.
That is it! You can now repeat the same process to manually replace any corrupted files.
Scan Other Non-OS Volumes using SFC
It may be possible that you are running more than one operating system on your PC, and not all of them can be in the same drive (usually the C drive). In that case, you must direct the SFC scan to attempt and repair another drive.
Furthermore, you can also direct it to scan external drives, such as USB flash drives, SD cards, etc.
Here is how to do so:
Note: Since SFC can only fix missing and corrupted files, it can only attempt to repair drives with a Windows operating system in it.
-
Open Command Prompt with elevated privileges.
-
Now use the following cmdlet to scan another drive while replacing DriveLetter with the drive letter for the volume you want to scan:
sfc/scannow/offbootdir=DriveLetter: /offwindir=DriveLetter:\Windows
The scan will now attempt to repair any corrupted or missing files that you selected other than the C drive.
How to Fix “Windows Resource Protection Could Not Start The Repair Service”
It may be possible that you encounter the following error while trying to run an SFC scan on your computer:
Windows Resource Protection could not start the repair service
If so, here are a few things you can do to mitigate this issue:
Start Dependency Service
It may be possible that a dependency service named “Windows Modules Installer (Trusted Installer)” isn’t running on your computer, preventing the scan from happening. In that case, the service needs to be enabled.
-
Open the Services console by typing in services.msc in the Run Command box.
Open Services console -
Here, scroll down and right-click on the service “Windows Modules Installer” and then click Properties from the context menu.
Open service properties -
From the popup, select “Startup Type” as Automatic, then click Start. When the service starts, click Apply and Ok to save the changes.
Enable and start service -
Try rerunning the SFC scan.
Learn other methods to enable and disable Windows services.
Disable Turbo Memory
Intel Turbo Memory is a feature that allows NAND memory modules to power up, access programs, and write data on the hard drive much quicker than usual. This feature can be controlled through the system BIOS.
If you experience an SFC scan suddenly stops or cannot complete its job, then you must disable Turbo Memory from the BIOS settings.
Learn how to access BIOS.
Modify Security Descriptors
A Security Descriptor contains security information that may be associated with a securable object. It may be possible that critical Security Descriptors may have corrupted in the WinSXS folder where critical files are stored.
To mitigate this issue, perform the following task:
-
Launch the Command Prompt with administrative rights.
-
Now run the following cmdlet:
ICACLS C:\Windows\winsxs
Modify Security Descriptors -
Now restart your computer and try rerunning the SFC scan.
Other Mitigation Methods
If you encounter the said error, there are other things you can also perform which we have already discussed above in this post. Here is a list of additional steps you can take:
- Run Check Disk Utility.
- Run DISM utility.
- Run SFC scan in Safe Mode.
- Replace corrupted files manually.
Frequently Asked Questions
Does SFC ScanNow fix anything?
Short answer: Yes, it does. However, the SFC tool itself can occasionally encounter errors, which are also fixable.
How to run SFC scan?
Run the following cmdlet in the Command Prompt:
sfc /scannow
Is the SFC scan safe?
Yes, the SFC scan is completely safe. In fact, you can even run it if nothing is wrong with your computer, just to ensure your device’s integrity.
What does SFC ScanNow actually do?
The SFC ScanNow cmdlet scans all protected files and replaces corrupted files with a cached copy that has been kept in its original shape.
Can you exit SFC scannow?
Yes, it is safe to cancel the scan. However, we do suggest that you allow it to be completed as it causes no harm. If you find that it is stuck you can cancel it using the CTRL + C keys simultaneously.
Does SFC ScanNow improve performance?
If the scan is able to fix critical files, it can sometimes improve the system’s overall performance and speed since the protected files are now as they should be.
Can SFC ScanNowfix BSoDs?
Potentially, yes. BSoDs are often caused by corrupted or missing files, and this is the one thing SFC is good at.
The sfc command is a Command Prompt command that can be used to verify and replace important Windows system files. Many troubleshooting steps advise the use of the sfc command.
System File Checker is a very useful tool to use when you suspect issues with protected Windows files, like many DLL files.
Sfc Command Availability
The sfc command is available from within the Command Prompt in most Windows operating systems, including Windows 11, Windows 10, Windows 8, Windows 7, Windows Vista, Windows XP, and Windows 2000.
System File Checker has been part of Windows Resource Protection since Windows Vista, and is sometimes referred to as Windows Resource Checker in those operating systems.
In Windows XP and Windows 2000, this tool is part of Windows File Protection.
Sfc Command Syntax
Its basic form, this is the syntax required to execute System File Checker options:
sfc options [=full file path]
Or, more specifically, this is what it looks like with options:
sfc [/scannow] [/verifyonly] [/scanfile=file] [/verifyfile=file] [/offbootdir=boot] [/offwindir=win] [/?]
How to Read Command Syntax
The availability of sfc command switches may differ somewhat from operating system to operating system.
Sfc Command Options | |
---|---|
Item | Description |
/scannow | This option instructs sfc to scan all protected operating system files and repair as necessary. |
/verifyonly | This sfc command option is the same as /scannow but without repairing. |
/scanfile=file | This sfc option is the same as /scannow but the scan and repair is only for the specified file. |
/offbootdir=boot | Used with /offwindir, this sfc option is used to define the boot directory (boot) when using sfc from outside of Windows. |
/offwindir=win | This sfc option is used with /offbootdir to define the Windows directory (win) when using sfc offline. |
/? | Use the help switch with the sfc command to show detailed help about the command’s several options. |
Sfc Command Examples
Here are some examples of the different ways you can use this command:
Scan and Replace All Corrupt Files
sfc /scannow
Here, the System File Checker utility is used to scan and then automatically replace any corrupt or missing system files. The /scannow option is the most commonly used switch for the sfc command.
Repair a Specific File
sfc /scanfile=c:\windows\system32\ieframe.dll
This sfc command is used to scan ieframe.dll and then repair it if an issue is found.
Scan a Different Windows Installation
sfc /scannow /offbootdir=c:\ /offwindir=c:\windows
In the next example, protected Windows files are scanned and repaired if necessary (/scannow), but this is done so with a different installation of Windows (/offwindir=c:\windows) on a different drive (/offbootdir=c:\).
The above example is how you would use the sfc command from the Command Prompt in System Recovery Options or from a different installation of Windows on the same computer.
Scan Everything, But Don’t Repair
sfc /verifyonly
With the /verifyonly option, System File Checker will scan all protected files and report any issues, but no changes are made.
Depending on how your computer was set up, you may need access to your original Windows installation disc or flash drive to allow file repairs.
Sfc Related Commands & More Information
The sfc command is often used with other Command Prompt commands, such as the shutdown command so that you can restart your computer after running System File Checker.
If Windows needs a copy of a file to replace the corrupt one with, it’ll get it from C:\Windows\WinSxS\Backup\. If that source has been compromised, Windows will access the internet to download the correct files from Microsoft’s website.
See Microsoft’s piece on System File Checker for more information you may find useful.
Thanks for letting us know!
Get the Latest Tech News Delivered Every Day
Subscribe