Windows deployment image servicing and management dism

Для проверки целостности системных файлов и восстановления поврежденных файлов (библиотек) компонентов в Windows (Windows Server) можно использовать команды SFC

Для проверки целостности системных файлов и восстановления поврежденных файлов (библиотек) компонентов в 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:WindowsWinSxS).

Утилита SFC записывает все свои действия в лог-файл
windir%logscbscbs.log
. Для всех записей, оставленных SFC в файле CBS.log проставлен тег [SR]. Чтобы выбрать из лога только записи, относящиеся к SFC, выполните команду:

findstr /c:"[SR]" %windir%LogsCBSCBS.log >"%userprofile%Desktopsfc.txt"

Если команда sfc /scannow возвращает ошибку “
Программа защиты ресурсов Windows обнаружила повреждённые файлы, но не может восстановить некоторые из них / Windows Resource Protection found corrupt files but was unable to fix some of them
”, скорее всего утилита не смогла получить необходимые файла из хранилища компонентов (образа) Windows.

sfc /scannow Программа защиты ресурсов 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 как поврежденный и возможно ли исправить его.

DISM /CheckHealth - проверка повреждений в образе 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.

DISM Cleanup-Image ScanHealth проверить хранилище компонентов 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 /Online /Cleanup-Image /RestoreHealth - восстановление образа windows 10

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).

DISM /RestoreHealth Error 0x800f081f, The source files could not be found<

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

  • Установочный диск/флешка/iso образ Windows
  • Смонтированный файл wim
  • Папка sourcesSxS с установочного диска
  • Файл install.wim с установочным образом Windows

Вы можете указать WIM или ESD файл с оригинальным установочным образом Windows, который нужно использовать в качестве источника для восстановления файлов системы. Предположим, вы смонтировали установочный ISO образ Windows 11 в виртуальный привод D:.

Примечание. Для восстановления поврежденных файлов в хранилище компонентов из локального источника версия и редакция Windows в образе должна полностью совпадать с вашей.

С помощью следующей PowerShell команды проверьте, какая версия Windows установлена на вашем компьютере:

Get-ComputerInfo |select WindowsProductName,WindowsEditionId,WindowsVersion, OSDisplayVersion

powershell Get-ComputerInfo получить номер билда и редакцию windows

Выведите список доступных версий Windows в установочном образе:

Get-WindowsImage -ImagePath "D:sourcesinstall.wim"

В нашем случае образ Windows 11 Pro в образе install.wim имеет
ImageIndex = 6
.

index версии windows в wim файле

Для восстановления хранилища компонентов из локального WIM/ESD файла с блокированием доступа в интернет, выполните следующую команду (не забудьте указать ваш индекс версии Windows в файле):

DISM /online /cleanup-image /restorehealth /source:WIM:D:sourcesinstall.wim:6  /limitaccess

Или:
DISM /online /cleanup-image /restorehealth /source:ESD:D:sourcesinstall.esd:6  /limitaccess

dism restorehealth source: восстановить хранилище компонентов из оригинального образа Windows на установочном диске, ISO, WIM файле

Если при запуске появляется

  • Ошибка Error: 50: DISM does not support servicing Windows PE with the /Online option, значит ваша DISM считает, что вы используете WinPE образWindows. Чтобы исправить это, удалите ветку реестра HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlMiniNT.
  • Ошибка DISM Error 87: проверьте правильно написания команды, убедитесь что вы используете версию DISM для вашей версии Windows (обычно бывает при загрузке через WinPE/WinRE).

Утилита DISM пишет подробный журнал сканирования и восстановления системных файлов в файл
C:WindowsLogsDISMdism.log
.

После восстановления хранилища компонентов вы можете запустить утилиту проверки системных файлов
sfc /scannow
. Скорее всего она успешно восстановит поврежденные файлы:

Программа защиты ресурсов Windows обнаружила поврежденные файлы и успешно их восстановила. 
Windows Resource Protection found corrupt files and successfully repaired them.

sfc /scannow Программа защиты ресурсов Windows обнаружила поврежденные файлы и успешно их восстановила

Если все системные файлы целы, появится сообщение:

Windows Resource Protection did not find any integrity violations

Восстановление образа Windows с помощью PowerShell

В версии PowerShell в Windows 10/11 и Windows Server 2022/2019 есть аналоги рассмотренных выше команд DISM. Для сканирования хранилища компонентов и поиска повреждений в образе выполните:

Repair-WindowsImage -Online –ScanHealth

Repair-WindowsImage -Online –ScanHealth ImageHealth State: Healthy

Если ошибок в хранилище компонентов не обнаружено, появится сообщение:

ImageHealth State: Healthy

Для запуска восстановления системных компонентов и файлов наберите:


Repair-WindowsImage -Online -RestoreHealth

При отсутствии доступа к интернету эта команда может зависнуть в процессе восстановления образа. Вы можете восстановить системные компоненты из локальной копии образа Windows в виде WIM/ESD файла, скопированного с установочного ISO образа Windows 10 (здесь также нужно указать индекс версии Windows в wim файле в качестве источника восстановления):

Repair-WindowsImage -Online -RestoreHealth -Source D:sourcesinstall.wim:5 –LimitAccess

DISM: восстановление поврежденного хранилища компонентов, если Windows не загружается

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

  1. Для этого загрузите компьютер с установочного образа Windows (проще всего создать загрузочную USB флешку с Windows 10/11 с помощью Media Creation Tool) и на экране начала установки нажмите
    Shift + F10
  2. Чтобы разобраться с буквами дисков, назначенных в среде WinPE, выполните команду
    diskpart
    ->
    list vol
    (в моем примере диску, на котором установлена Windows присвоена буква C:, эту букву я буду использовать в следующих командах);diskpart получить буквы дисков
  3. Проверим системные файлы и исправим поврежденные файлы командой:
    sfc /scannow /offbootdir=C: /offwindir=C:Windows

    sfc /scannow /offbootdir=C: /offwindir=C:Windows
  4. Для исправления хранилища компонентов используйте следующую команду (в качестве источника для восстановления компонентов мы используем WIM файл с установочным образом Windows 10, с которого мы загрузили компьютер):
    Dism /image:C: /Cleanup-Image /RestoreHealth /Source:WIM:D:sourcesinstall.wim:6
    Dism /image /RestoreHealth offline в windows 10
  5. Если на целевом диске недостаточно места, то для извлечения временных файлов нам понадобится отдельный диск достаточного размера, например F:, на котором нужно создать пустой каталог:
    mkdir f:scratch
    и запустить восстановление хранилища компонентов командой:
    Dism /image:C: /Cleanup-Image /RestoreHealth /Source:D:sourcesinstall.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 на полную без переустановки.
Windows 10 DISM and SFC repair
Windows 10 DISM and SFC repair
(Image credit: Windows Central)

On Windows 10, the Deployment Image Servicing and Management is a command-line tool that allows administrators to prepare, modify, and repair system images, including Windows Recovery Environment, Windows Setup, and Windows PE (WinPE). However, you can also use it with the local recovery image to fix system problems.

Typically, when you need to troubleshoot a specific error, figure out why the computer no longer boots correctly, or resolve performance issues, you can use the System File Checker tool to replace missing or corrupted system files using the recovery image. The caveat utilizing this approach is that if one or more Windows 10 files in the local image are damaged, the SFC command won’t work. In this scenario, you can use the «install.wim» image with DISM to repair the image and then use the SFC tool to fix the setup without having to reinstall Windows.

In this Windows 10 guide, we will walk you through the steps to use the DISM and SFC tools to bring a computer back to a healthy working state without the need for reinstallation.

  • How to run DISM to repair image of Windows 10
  • How to run SFC to repair problems of Windows 10

Warning: The commands outlined in this guide are non-destructive, but since you will be making system changes, it is still recommended to create a temporary full backup before proceeding.

How to use DISM to repair image of Windows 10

On Windows 10, the DISM command tool includes three options to repair an image, including «CheckHealth,» «ScanHealth,» and «RestoreHealth,» which you want to use in order. Also, depending on the issue, you can use the «RestoreHealth» option to fix the locally available image using different source files.

DISM command with CheckHealth option

The CheckHealth option with the DISM tool allows you to determine any corruptions inside the local Windows 10 image. However, the option does not perform any repairs.

To check the Windows 10 image for issues with DISM, use these steps:

  1. Open Start.
  2. Search for Command Prompt, right-click the top result, and select the Run as administrator option.
  3. Type the following command to perform a quick check and press Enter:DISM /Online /Cleanup-Image /CheckHealth

DISM CheckHealth

Source: Windows Central (Image credit: Source: Windows Central)

Once you complete the steps, the Deployment Image Servicing and Management tool will run and verify any data corruption that may require fixing.

DISM command with ScanHealth option

The ScanHealth option does a more advanced scan to find out whether the image has any problems.

To check image problems with the ScanHealth option, use these steps:

  1. Open Start.
  2. Search for Command Prompt, right-click the top result, and select the Run as administrator option.
  3. Type the following command to perform an advanced DISM scan and press Enter:DISM /Online /Cleanup-Image /ScanHealth

DISM ScanHealth

Source: Windows Central (Image credit: Source: Windows Central)

After you complete the steps, the scan may take several minutes to check whether the Windows 10 image needs repairing.

DISM command with RestoreHealth option

If there are problems with the system image, use DISM with the RestoreHealth option to automatically scan and repair common issues.

To repair Windows 10 image problems with the DISM command tool, use these steps:

  1. Open Start.
  2. Search for Command Prompt, right-click the top result, and select the Run as administrator option.
  3. Type the following command to repair the Windows 10 image and press Enter:DISM /Online /Cleanup-Image /RestoreHealthQuick note: If the command appears stuck, this is normal behavior. After a few minutes, the process will complete successfully.

DISM RestoreHealth on Windows 10

Source: Windows Central (Image credit: Source: Windows Central)

Once you complete the steps, the tool will connect to Windows Update online to download and replace damaged files (as necessary).

Fix problems with DISM using install.wim image

The Deployment Image Servicing and Management command usually doesn’t cause issues. However, if the tool finds problems replacing the damaged files or the computer isn’t connected to the internet, you will need to provide another image using the Source option. Typically, you can use an «install.wim» or «install.esd» file from another device, bootable install media, or Windows 10 ISO file. You only need to make sure that the files match the version, edition, and language of the version of Windows 10 you are trying to fix.

Download Windows 10 ISO file

If you need to use another file source, it is recommended to use the Media Creation Tool to download a fresh copy of Windows 10.

To download the ISO file of Windows 10, use these steps:

  1. Open this Microsoft support website (opens in new tab).
  2. Click the Download tool now button.
  3. Double-click the MediaCreationToolxxxx.exe file to launch the setup.
  4. Click the Accept button to agree to the terms.
  5. Select the Create installation media (USB flash drive, DVD, or ISO file) for another PC option.

Media Creation Tool create media for another PC

Source: Windows Central (Image credit: Source: Windows Central)
  1. Click the Next button.
  2. Click the Next button again.

Select language, architecture, and edition

Source: Windows Central (Image credit: Source: Windows Central)
  1. Select the ISO file option.

Media Creation Tool ISO file option

Source: Windows Central (Image credit: Source: Windows Central)
  1. Click the Next button.
  2. Select the destination to store the Windows 10 ISO file.
  3. Click the Save button.
  4. Click the link to open the file location with File Explorer.

Open Windows 10 ISO location

Source: Windows Central (Image credit: Source: Windows Central)
  1. Click the Finish button.
  2. Double-click the Windows.iso file to mount the image.
  3. Under the «This PC» section, confirm the drive letter for the mount point.

Windows 10 ISO driver letter

Source: Windows Central (Image credit: Source: Windows Central)

After you complete the steps, you can continue with the DISM tool using the «Source» option to repair the local image.

Fix Windows 10 recovery image

To run Deployment Image Servicing and Management tool with an alternate source (install.wim) image, use these steps:

  1. Open Start.
  2. Search for Command Prompt, right-click the top result, and select the Run as administrator option.
  3. Type the following command to repair the Windows 10 image and press Enter:DISM /Online /Cleanup-Image /RestoreHealth /Source:E:Sourcesinstall.wimIn the command, replace «F» with the ISO mount point drive letter in File Explorer.

DISM RestoreHealth with install.wim file

Source: Windows Central (Image credit: Source: Windows Central)
  1. (Optional) Type the following command to limit the use of Windows Update and press Enter:DISM /Online /Cleanup-Image /RestoreHealth /Source:ESourcesinstall.wim /LimitAccess
  2. (Optional) Type the following variant of the previous command to accomplish the same task and press Enter:DISM /Online /Cleanup-Image /RestoreHealth /Source:wim:E:Sourcesinstall.wim:1 /LimitAccessIn the command, change E:Sources, for the path to the «install.wim» file.

Once you complete the steps, the command will scan and repair the problems using the «install.wim» file you specified as the alternative source.

Fix problems with DISM using ESD image

If you have an encrypted «install.esd» image, it’s possible to use it to repair the damaged files on Windows 10.

To use DISM with an «install.esd» image file as the source to repair Windows 10, use these steps:

  1. Open Start.
  2. Search for Command Prompt, right-click the top result, and select the Run as administrator option.
  3. Type the following command to repair the image with an «install.esd» file and press Enter:DISM /Online /Cleanup-Image /RestoreHealth /Source:C:ESDWindowssourcesinstall.esdIn the command, change C:ESDWindowssources with the path to the location of the «.esd» file (if different).

DISM Restorehealth install.esd

Source: Windows Central (Image credit: Source: Windows Central)
  1. (Optional) Type the following command to limit the use of Windows Update and press Enter:DISM /Online /Cleanup-Image /RestoreHealth /Source:C:ESDWindowssourcesinstall.esd /LimitAccess
  2. (Optional) Type the following variant of the previous command to accomplish the same task and press Enter:DISM /Online /Cleanup-Image /RestoreHealth /Source:esd:C:ESDWindowssourcesinstall.esd:1 /LimitAccess
  3. (Optional) Type the following command to use an install.esd file located in another drive and press Enter:DISM /Online /Cleanup-Image /RestoreHealth /Source:E:Sourcesinstall.esdIn the command, replace E:Sources with the path to the location of the «install.esd» file.

After you complete the steps, the tool will repair the damaged files using the files included in the «install.esd» image.

How to run SFC to repair problems on Windows 10

The above instructions will resolve problems with the system image, not the issues with the Windows 10 installation. After restoring the image to a healthy state, use the System File Checker (SFC) command tool to repair the current setup.

To use the SFC command tool to repair Windows 10 problems, use these steps:

  1. Open Start.
  2. Search for Command Prompt, right-click the top result, and select the Run as administrator option.
  3. Type the following command to repair the installation and press Enter:SFC /scannowQuick tip: If errors are found, you may want to run the command around three times to ensure that everything was fixed correctly.

Windows 10 installation repair with SFC

Source: Windows Central (Image credit: Source: Windows Central)

Once you complete the steps, the System File Checker tool will repair the system files using the local image files, and the log files will be saved on

%windir%/Logs/CBS/CBS.log

and

%windir%LogsDISMdism.log

, which you can view to get more details about the process.

You can use this guide to learn more ways to use the SFC tool to fix problems on Windows 10.

More Windows resources

For more helpful articles, coverage, and answers to common questions about Windows 10 and Windows 11, visit the following resources:

  • Windows 11 on Windows Central — All you need to know
  • Windows 11 help, tips, and tricks
  • Windows 10 on Windows Central — All you need to know

Get the best of Windows Central in in your inbox, every day!

Mauro Huculak is technical writer for WindowsCentral.com. His primary focus is to write comprehensive how-tos to help users get the most out of Windows 10 and its many related technologies. He has an IT background with professional certifications from Microsoft, Cisco, and CompTIA, and he’s a recognized member of the Microsoft MVP community.

Every admin knows the usage of Deployment Image Servicing and Management (DISM) for mounting and customizing Windows images. DISM is a comprehensive and varied utility, providing many lesser-known capabilities around servicing applications and drivers, applying unattend.xml, changing your Windows edition, or even reverting Windows to a previous OS installation.

Contents

  1. Mounting and servicing a WIM
  2. Capturing an image
  3. Adding and removing drivers
  4. Lesser-known capabilities of DISM
    • Set the system user interface language
    • Set the input locale and keyboard layout
    • Set the time zone in the Windows image
    • Getting and changing the Windows edition
    • Update packages or other services using an unattend.xml answer file
    • Revert a PC to a previous Windows installation
    • Remove previous Windows versions
    • Repair Windows images and VHD/VHDX files
  5. Manage AppX and install MSU files
    • Manage provisioned AppX packages
    • Remove the AppX package
    • Add and remove packages
  6. Add or remove optional and on-demand features
  7. Manage file associations
  8. Wrapping up
  • Author
  • Recent Posts

Brandon Lee has been in the IT industry 15+ years and focuses on networking and virtualization. He contributes to the community through various blog posts and technical documentation primarily at Virtualizationhowto.com.

The DISM command is known for working with Windows images and FFU files, and can even be used for working with VHD and VHDX disks for services. It is built into Windows and can be called from the command line, Windows PowerShell, and PowerShell Core.

It is important to note that the DISM.exe command line tool and DISM PowerShell cmdlets have corresponding functionalities. However, you can also call the DISM.exe tool from a PowerShell environment. Microsoft has a good comparison between the DISM.exe command line options and PowerShell’s equivalent cmdlets.

Running the DISM command and exploring the options

Running the DISM command and exploring the options

The functionality provided by DISM allows IT admins to perform servicing tasks that fall within two main use cases:

  • Servicing the image itself: Admins can configure and customize the .wim image, including adding and removing drivers, configuring language settings, adding or removing Windows features, and even changing the Windows edition.
  • Managing the data in the Windows image: Using DISM, you can inventory the image components, drivers, and updates, split the image, and delete or add images within a .wim file.

Remember that DISM can only service images for operating system versions equal to or older than the currently installed version of DISM. In addition, it always requires a session with elevated permissions, even to show the online help.

Mounting and servicing a WIM

DISM is primarily used to capture and restore images of Windows machines for subsequent mass rollout to devices. You can also use DISM for deployment with Microsoft Deployment Toolkit (MDT). Conversely, it can also service images captured with MDT.

Mounting, servicing, and unmounting a WIM comprise the following commands (in this example, we add a language pack to the image):

dism /Mount-Wim /MountDir:mount /wimfile:boot.wim /index:1
dism /image:mount /Add-Package /PackagePath: "e: lp.cab"
dism /Unmount-Wim /MountDir:mount /commit

If you want to apply the changes to the images, use /Discard instead of /commit when unmounting. You can save changes to the WIM file without unmounting it using this command:

DISM.exe /Commit-Image /MountDir:mount

Capturing an image

You can capture Windows images using a command like this:

Dism /Capture-Image /ImageFile:install.wim /CaptureDir:D: /Name:Drive-D

To apply a Windows image to a device, use the following:

Dism /apply-image /imagefile:N:Imagesmy-windows-partition.wim /index:1 /ApplyDir:W:

Adding and removing drivers

If you are deploying the same image across multiple hardware configurations, the reference image may not contain all the drivers needed to cover the different vendor hardware. DISM has you covered with the ability to add drivers to the offline Windows image. In the example below, you can add all the needed drivers to a folder and recursively add the drivers it contains to the Windows image.

Dism /image:C:testoffline /Add-Driver /driver:C:testdrivers /recurse

You can also remove drivers using DISM:

Dism /image:C:testoffline /Remove-Driver /driver:oem1.inf

Lesser-known capabilities of DISM

Note the following capabilities of DISM that are not so apparent and can be used for a wide range of operations:

  • Set the system user interface (UI) language.
  • Set the input locale and keyboard layout.
  • Set the time zone in the Windows image.
  • Get target Windows edition information, and change the Windows edition.
  • Add and remove drivers.
  • Update packages or other services using an unattend.xml answer file.
  • Revert a PC to a previous Windows installation, and remove previous Windows versions.
  • Repair Windows images and VHD/VHDX files.
  • Manage AppX and install MSU files.
  • Add or remove optional features.
  • Manage file associations.

Set the system user interface language

Using DISM, you can manage and set the system user interface (UI) language for a Windows image. Let’s say you had taken a reference Windows image for deployment. If you have multiple locations where you want to deploy the image, instead of having to capture a reference image from scratch, you can use DISM to change the UI language for each location.

Dism /image:C:testoffline /Set-SysUILang:en-US

Set the input locale and keyboard layout

DISM allows changing the input locale and keyboard layout, which, again, is useful if you need to do so for an offline image without recapturing it before deployment.

Dism /image:C:testoffline /Set-InputLocale:fr-fr
Dism /image:C:testoffline /Set-InputLocale:0410:00010410

Set the time zone in the Windows image

You can set the time zone for an offline image, allowing the servicing of images to customize the time zone of a captured image before deploying it to multiple time zones.

Dism /image:C:testoffline /Set-TimeZone"Central Standard Time"

None of the above commands can be applied to a live system because the international provider doesn’t support the /online switch.

Getting and changing the Windows edition

Suppose you want to check the available Windows editions that can be targeted for a specific Windows image (online and offline):

Dism /Image:C:testoffline /Get-TargetEditions

Show available Windows edition for the current system

Show available Windows edition for the current system

To change the Windows edition to a higher target edition, you need to use the /AcceptEula switch and enter a product key to unlock the higher edition of Windows.

Dism /online /Set-Edition:<edition name> /AcceptEula /ProductKey:12345-67890-12345-67890-12345

Update packages or other services using an unattend.xml answer file

Much like using an unattend.xml file when installing Windows, you can use the unattend.xml file to update software packages and services using DISM.

Dism /image:C:testoffline /Apply-Unattend:C:testanswerfilesmyunattend.xml

Revert a PC to a previous Windows installation

DISM also allows you to manage Windows versions and revert to different versions of Windows. To revert to a previous version of Windows, you can use the following command:

DISM /Online /Initiate-OSUninstall [/NoRestart|/Quiet]

Remove previous Windows versions

If you want to remove the ability to revert to a previous version of Windows and free up space, DISM can delete the dispensable OS:

DISM /Online /Remove-OSUninstall

Repair Windows images and VHD/VHDX files

One of the handy features of DISM is its ability to repair Windows online and offline images, as well as VHD/VHDX files. You can scan a Windows image or VHD/VHDX file for corruption with the following:

Dism /Online /Cleanup-Image /ScanHealth

Check system integrity with DISM

Check system integrity with DISM

To check for any corruption detected and clean up the image, you can use the following:

Dism /Online /Cleanup-Image /CheckHealth

To repair an image, you can use the following:

Dism /Image:C:offline /Cleanup-Image /RestoreHealth /Source:c:testmountwindows
Dism /Online /Cleanup-Image /RestoreHealth /Source:c:testmountwindows /LimitAccess

Manage AppX and install MSU files

DISM is able to manage app packages (.appx or .appxbundle) and operating system packages (CAB or MSU files). So, you can avoid recapturing a reference image.

Manage provisioned AppX packages

Get provisioned AppX packages:

Dism /Image:C:testoffline /Get-ProvisionedAppxPackages

Add provisioned AppX packages:

dism.exe /Add-ProvisionedAppxPackage {/FolderPath:<App_folder_path> [/SkipLicense] [/CustomDataPath:<custom_file_path>]  /PackagePath:<main_package_path> [/DependencyPackagePath:<dependency_package_path>] {[/LicensePath:<license_file_path>] [/SkipLicense]} [/CustomDataPath:<custom_file_path>]} [/Region:<region>]

Remove the AppX package

Dism /Image:C:testoffline /Remove-ProvisionedAppxPackage /PackageName:<PackageName>

Add and remove packages

DISM can also be used to manage operating system packages with CAB or MSU files:

Dism /Image:C:testoffline /Get-Packages

Add a package to a Windows image:

Dism /Add-Package /PackagePath:<path_to_cabfile> [/IgnoreCheck] [/PreventPending]

Remove a package:

Dism /Image:C:testoffline /LogPath:C:testRemovePackage.log/Remove-Package {/PackageName:<name_in_image> | /PackagePath:<path_to_cabfile>}

Add or remove optional and on-demand features

Another great DISM capability is managing optional features in your online and offline images.

To find the installed Windows features in an image, you can use the following:

Dism /online /Get-Features
Dism /Image:C:testoffline /Get-Features

To add Windows features (e.g., TFTP), use the following:

Dism /online /Enable-Feature /FeatureName:TFTP /All
Dism /Image:C:testoffline /Enable-Feature /FeatureName:TFTP /All

To remove Windows features:

Dism /online /Disable-Feature /FeatureName:TFTP
Dism /Image:C:testoffline /Disable-Feature /FeatureName:TFTP

Microsoft calls feature packages either optional features or features on demand, although the distinction between these two is unclear. This command shows all available capabilities, present as well as not present:

Dism /online /Get-Capabilities

To install the RSAT tool for WSUS, you use the utility as follows:

Dism /online /Add-Capability /CapabilityName:Rsat.WSUS.Tools~~~~0.0.1.0

Install RSAT for WSUS using DISM

Install RSAT for WSUS using DISM

To remove it, use /Remove-Capability instead of /Add-Capability.

Manage file associations

DISM can define which application opens a specific file type (file associations) for both online Windows installations and offline images.

If you have a source machine from which you want to export the file associations, you can do that with DISM:

Dism.exe /Online /Export-DefaultAppAssociations:C:AppAssoc.xml

Export file associations to an XML file

Export file associations to an XML file

You can then take the exported XML file and import the file to a new target machine or image:

Dism.exe /Online /Import-DefaultAppAssociations:C:AppAssoc.xml
Dism.exe /Image:C:testoffline /Import-DefaultAppAssociations:C:AppAssoc.xml

You can also use XML with group policies if you want to apply it to many PCs.

Wrapping up

The DISM command-line utility allows IT admins to perform all sorts of tasks and operations on Windows images and virtual hard disks. It is generally used with the typical duties of capturing, applying, and mounting Windows images.

Subscribe to 4sysops newsletter!

However, DISM has many capabilities that admins may not be aware of. As shown, you can perform operations on applications, drivers, Appx packages, and operating system packages. In addition, they can change the input locale, time zone, and keyboard layout, and even control the Windows edition, control file associations, repair images and VHD/VHDX files, and roll back to previous Windows installations.

Всякий раз, когда что-то идет не так с компьютером или ноутбуком, есть ряд инструментов для устранения неполадок, которые вы можете выполнить, чтобы попытаться устранить проблему. В Windows 10/8/7 есть несколько встроенных команд, которые можно использовать для проверки и восстановления поврежденных системных файлов, которые со временем вызывают проблемы при изменении.

Одним из способов устранения неполадок, связанных с Windows, является проверка системы и восстановление системных файлов. Это может помочь во всех типах проблем, таких как медленная система, синий экран смерти, внезапные сбои питания и сбои системы.

SFC и DISM — Средство проверки системных файлов, которое сканирует компьютер на предмет любого повреждения или изменений в системных файлах, которые в противном случае могли бы помешать нормальной работе вашего ПК. Инструменты заменяет файл правильной версией, чтобы обеспечить бесперебойную работу. С помощью командной строки можно попытаться сканировать и восстановить системные файлы поздних операционных систем, как Windows 10/8/7 /Vista.

Проверка и Восстановление системных файлов

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

  1. chkdsk c: /f /r
  2. sfc /scannow
  3. DISM /Online /Cleanup-Image /RestoreHealth

Проверка и Восстановление системных файлов


Ниже разберем более подробно команды, что делать с ошибками при вводе команд, как использовать SFC и DISM из образа и дополнительных параметров и, как прочесть файл CBS.log, когда появляется ошибка «Программа защиты ресурсов Windows обнаружила поврежденные файлы и не смогла восстановить. Подробные сведения в файле CBS.Log, который находится по пути: C:WindowsLogsCBSCBS.log«.

channel

1. Использование инструмента System File Checker (SFC)

Запустите командную строку (CMD) от имени администратора. Нажмите «поиск» и напишите просто «cmd» или «командная строка», далее по ней правой кнопкой мыши и запуск от имени админа.

Задайте ниже команду и дождитесь окончания процесса:

  • sfc /scannow

CMD sfc /scannow

Примечание: После сканирования вашей системы будет выдан один из трех результатов:

  • Ошибок системных файлов не будет.
  • Будут ошибки системных файлов и Windows восстановит их автоматически.
  • Windows обнаружила ошибки, но не может восстановить некоторые из них.

Если у вас показывает вариант 3, что ошибка обнаружена и система не может восстановить, то загрузитесь в безопасном режиме и проделайте заново процедуру. Советую отключить шифрование EFS и Bitlocker, если они были включены. Если SFC все ровно не смог восстановить файлы, то попробуйте ниже способ через дополнительные параметры и прибегните к способу 2 (DISM).

sfc /scannow обнаружило ошибку и не может восстановить

Запуск SFC через дополнительные параметры

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

  • Откройте «Параметры» > «Обновления и безопасность» > «Восстановление«.
  • Справа найдите «Особые варианты загрузки» и нажмите «Перезагрузить сейчас».

особые варианты загрузки, перезагрузить сейчас

В дополнительных параметрах перейдите «Поиск и устранение неисправностей» > «Дополнительные параметры» > «Командная строка».

Запуск командной строки при установки Windows 10

Далее задайте команду:

sfc /scannow /offbootdir=C: /offwindir=C:Windows

offbootdir offwindir

2. Использование инструмента Deployment Image and Service Management (DISM)

Если вышеуказанное не работает, есть один последний способ проверить повреждение в системных файлах и исправить их. Используем инструмент Deployment Image and Service Management (DISM). Команда работает с системами Windows 8/8.1/10. Откройте обратно командную строку от имени администратора и используйте следующую команду:

DISM /ONLINE /CLEANUP-IMAGE /RESTOREHEALTH

Процесс может занять длительное время с зависанием процентной шкалы. Закончив работу, перезагрузите компьютер и запустите обратно sfc /scannow, чтобы убедиться, что ошибок нет или ошибка пропала.

Восстановление системных файлов с помощью CMD DISM

Запуск DISM из образа Windows

Если выше команда DISM выдает ошибку повреждения компонентов хранилища, то можно восстановить файлы из ISO образа. Смонтируйте ISO образ Windows 10 в проводнике.

Примечание: Лучше, чтобы версия, язык и архитектура монтируемого образа, совпадала с текущей Windows 10, которая установлена.

Монтировать ISO Windows 10

Далее введите ниже команду и замените букву I на подключаемый образ. Откройте проводник (этот компьютер) и посмотрите букву диска.

DISM /Online /Cleanup-Image /RestoreHealth /Source:I:Sourcesinstall.esd

Запуск DISM из образа Windows

Анализ лога CBS, какие файлы не удалось восстановить

Если после сканирования системных файлов, программа защиты ресурсов Windows обнаружила поврежденные файлы, но не может восстановить некоторые из них, лог файл CBS может помочь определить, какие именно файлы повреждены. Для этого:

  • Перейдите по пути C:WindowsLogsCBS
  • Откройте файл CBS.log в блокноте или текстовом редакторе
  • В блокноте нажмите Ctrl+F, чтобы вызвать поиск
  • В поиске напишите Cannot repair member file, чтобы найти файлы, которые не удается восстановить
  • Если поиск не дал результатов, то найдите записи [SR] и вы обнаружите, что все они одинаковы 100 components
  • Ищите листая вручную любые изменения, отличные от 100 components, где вы и найдете поврежденный файл или указание
  • Ориентируетесь по времени, когда вы примерно запускали сканирование SFC, так как лог может быть и за вчерашний день

SR записи в CBS логе

Примечание: Лог журнала DISM находятся по пути C:WindowsLogsDISM (dism.log).



Смотрите еще:

  • Не работает кнопка Пуск в Windows 10?
  • Почему Пропал и Не Работает Звук в Windows 10?
  • 9 Причин Почему Компьютер с Windows Зависает
  • Диск загружен на 100% в диспетчере задач Windows 10
  • Ускоренная загрузка windows, настройка windows для быстрой работы

[ Telegram | Поддержать ]

Понравилась статья? Поделить с друзьями:
  • Windows delete all files in folder
  • Windows defender это приложение выключено групповой политикой
  • Windows defender этим параметром управляет ваш администратор
  • Windows defender что это как отключить
  • Windows date picker в excel 2013 скачать