Dism online windows server 2008 r2

Once your Server Core network etc are configured it’s time to enable/ disable Windows features and roles.

To enable/ disable/ list Windows features and roles it’s probably easiest to import the ServerManager module into PowerShell and use the three cmdlets provided. But just in case you are not into PowerShell, or don’t want to install PowerShell and it’s dependency .NET (you are on Server Core and PowerShell & .NET aren’t installed by default there) there are two alternatives.

DISM

DISM is short for Deployment Image Servicing and Management. As the name suggests, it’s a tool for managing the disk image using which you deploy Windows. Starting with Windows Vista the installation files of Windows are stored in a (file based) disk image called the Windows Imaging Format (WIM). DISM is a tool that can manage this disk image before it’s deployed to a computer. But DISM is not just about managing disk images before they are deployed; it can be used also to manage a running instance of a deployed image. The latter is what we are interested here.

Disk images prior to deployment are known as offline images. Disk images that are currently running as the OS within which DISM is invoked are called online images. When you are dealing with an online image you also pass the switch /online to DISM.

DISM was introduced with Windows 7/ Windows Server 2008 R2 and has a pretty straight-forward syntax:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

C:\Users\Administrator>dism /online /?

Deployment Image Servicing and Management tool

Version: 6.1.7600.16385

Image Version: 6.1.7600.16385

The following commands may be used to service the image:

...

PACKAGE SERVICING COMMANDS:

  /AddPackage             Adds packages to the image.

  /RemovePackage         Removes packages from the image.

  /EnableFeature         Enables a specific feature in the image.

  /DisableFeature         Disables a specific feature in the image.

  /GetPackages           Displays information about all packages in

                            the image.

  /GetPackageInfo         Displays information about a specific package.

  /GetFeatures           Displays information about all features in

                            a package.

  /GetFeatureInfo         Displays information about a specific feature.

  /CleanupImage           Performs cleanup and recovery operations on the

                            image.

...

The switches of interest to use are /Enable-Feature, /Disable-Feature, and /Get-Features.

To get a list of available features:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

C:\Users\Administrator>dism /online /getfeatures /?

Deployment Image Servicing and Management tool

Version: 6.1.7600.16385

Image Version: 6.1.7600.16385

/GetFeatures [/Format:] [/PackagePath:]

  [/PackageName:]

  Displays information about all features found in a specific package. If you

  do not specify a package name or path, all features in the image will be

  listed. /PackagePath can point to either a .cab file or a folder. Use the

  /Format option to specify a table or list format for the output. If /Format

  is not specified the option is formatted as a list.

...

C:\Users\Administrator>dism /online /getfeatures /format:table

Deployment Image Servicing and Management tool

Version: 6.1.7600.16385

Image Version: 6.1.7600.16385

Features listing for package : MicrosoftWindowsServerCorePackage~31bf3856ad364e35~amd64~~6.1.7600.16385

|

Feature Name                                                | State

|

NetworkLoadBalancingHeadlessServer                          | Disabled

SUACore                                                     | Disabled

SUACoreWOW64                                               | Disabled

WindowsServerBackup                                         | Disabled

WindowsServerBackupCommandlet                               | Disabled

MultipathIo                                                 | Disabled

DNSServerCoreRole                                        | Disabled

FRSInfrastructure                                          | Disabled

BitLocker                                                   | Disabled

...

C:\Users\Administrator>dism /online /enablefeature /featurename:ServerManagerPSHCmdlets

Deployment Image Servicing and Management tool

Version: 6.1.7600.16385

Image Version: 6.1.7600.16385

Enabling feature(s)

[==========================100.0%==========================]

The operation completed successfully.

C:\Users\Administrator>dism /online /getfeatures /format:table | find «PowerShell»

ActiveDirectoryPowerShell                                  | Disabled

MicrosoftWindowsPowerShell                                  | Disabled

MicrosoftWindowsPowerShellWOW64                            | Disabled

To enable a feature:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

C:\Users\Administrator>dism /online /enablefeature /?

Deployment Image Servicing and Management tool

Version: 6.1.7600.16385

Image Version: 6.1.7600.16385

/EnableFeature /FeatureName: [/PackageName:]

  Enables a specified feature. If the package name is not specified, the

  Windows Foundation package is assumed. Feature names are casesensitive.

...

C:\Users\Administrator>dism /online /enablefeature /featurename:MicrosoftWindowsPowerShell

Deployment Image Servicing and Management tool

Version: 6.1.7600.16385

Image Version: 6.1.7600.16385

Enabling feature(s)

[==========================100.0%==========================]

Error: 50

The operation completed but MicrosoftWindowsPowerShell feature was not enabled.

Ensure that the following parent feature(s) are enabled first. If they are already enabled, refer to the log file for further diagnostics.

NetFx2ServerCore

C:\Users\Administrator>dism /online /enablefeature /featurename:NetFx2ServerCore

Deployment Image Servicing and Management tool

Version: 6.1.7600.16385

Image Version: 6.1.7600.16385

Enabling feature(s)

[==========================100.0%==========================]

The operation completed successfully.

C:\Users\Administrator>dism /online /enablefeature /featurename:MicrosoftWindowsPowerShell

Deployment Image Servicing and Management tool

Version: 6.1.7600.16385

Image Version: 6.1.7600.16385

Enabling feature(s)

[==========================100.0%==========================]

The operation completed successfully.

C:\Users\Administrator>dism /online /enablefeature /featurename:ServerManagerPSHCmdlets

Deployment Image Servicing and Management tool

Version: 6.1.7600.16385

Image Version: 6.1.7600.16385

Enabling feature(s)

[==========================100.0%==========================]

The operation completed successfully.

As you can see, feature names are case sensitive (eugh!!), and DISM doesn’t automatically enable dependent features – we have to enable them ourselves (good in a way coz DISM won’t enable a whole bunch of dependencies without me realizing, but I wish there were a way to say go ahead and enable whatever’s required). In contrast, if you try enabling a feature using PowerShell with the ServerManager module, dependencies are automatically taken care of.

(Update: DISM in Windows Server 2012 and Windows 8 has a /all switch that automatically installs all the dependencies.)

The feature names are also not very intuitive – for instance to enable AD DS you need to enable the DirectoryServices-DomainController-ServerFoundation feature but that’s not very obvious coz of the ServerFoundation tacked at the end of the feature name, which makes you think it might be a scaled down version of AD DS. (Just as an aside: in the specific case of AD DS, even if you don’t enable the afore-mentioned feature yourself, dcpromo automatically enables it as part of its tasks). This TechNet article is helpful in understanding what the feature names are.

I also hate the fact the fact that there are so many switches to type, but hey, at least the names are logical and I am glad DISM doesn’t have any dependencies and works out of the box on Server Core too. PowerShell has much better switches, but you need DISM sort of to enable PowerShell and the ServerManage module features.

Apart from enabling and disabling features, it’s worth knowing that DISM can be used to upgrade between editions. Say if you are running Server Core Standard and want to move to Server Core Enterprise, DISM can do that.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

C:\Users\Administrator>dism /online /?

Deployment Image Servicing and Management tool

Version: 6.1.7600.16385

Image Version: 6.1.7600.16385

The following commands may be used to service the image:

WINDOWS EDITION SERVICING COMMANDS:

  /SetProductKey         Populates the product key into the offline image.

  /GetTargetEditions     Displays a list of Windows editions that an

                            image can be upgraded to.

  /GetCurrentEdition     Displays the editions of the specified image.

  /SetEdition             Upgrades the Windows image to a higher edition.

...

C:\Users\Administrator>dism /online /getcurrentedition

Deployment Image Servicing and Management tool

Version: 6.1.7600.16385

Image Version: 6.1.7600.16385

Current edition is:

Current Edition : ServerStandardCore

The operation completed successfully.

C:\Users\Administrator>dism /online /gettargeteditions

Deployment Image Servicing and Management tool

Version: 6.1.7600.16385

Image Version: 6.1.7600.16385

Editions that can be upgraded to:

Target Edition : ServerDataCenterCore

Target Edition : ServerEnterpriseCore

The operation completed successfully.

Read more about DISM and upgrading images at this TechNet article and blog post.

Lastly, DISM can also be used to query the installed drivers:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

C:\Users\Administrator>dism /online /getdrivers

Deployment Image Servicing and Management tool

Version: 6.1.7600.16385

Image Version: 6.1.7600.16385

Obtaining list of 3rd party drivers from the driver store...

Driver packages listing:

Published Name : oem0.inf

Original File Name : vboxguest.inf

Inbox : No

Class Name : System

Provider Name : Oracle Corporation

Date : 10/26/2012

Version : 4.2.4.0

Published Name : oem1.inf

Original File Name : vboxvideo.inf

Inbox : No

Class Name : Display

Provider Name : Oracle Corporation

Date : 10/26/2012

Version : 4.2.4.0

Published Name : oem2.inf

Original File Name : netkvm.inf

Inbox : No

Class Name : Net

Provider Name : Red Hat Inc.

Date : 2/13/2012

Version : 61.63.103.2200

The operation completed successfully.

Unfortunately while there is a /Add-Driver switch for adding drivers, it doesn’t work against an online image.

OCSetup

OCSetup is short for Optional Components Setup. This tool was introduced in Windows Vista/ Server 2008 specifically for Server Core. Windows Vista/ Server 2008 had the new modular architecture of roles and features, along with the Server Manager tool (GUI and command line) to manage these. However, Server Manager depends on .NET which is not enabled by default on Server Core, and so the OCSetup tool was provided for Server Core. This tool has a counterpart called OCList that gets a list of the optional components.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

C:\Users\Administrator>oclist |more

Use the listed update names with Ocsetup.exe to install/uninstall a server role or optional feature.

Adding or removing the Active Directory role with OCSetup.exe is not supported. It can leave your server in an unstable

state. Always use DCPromo to install or uninstall Active Directory.

===========================================================================

MicrosoftWindowsServerCorePackage

Not Installed:BitLocker

Not Installed:BitLockerRemoteAdminTool

Not Installed:CertificateServices

Not Installed:ClientForNFSBase

Not Installed:CoreFileServer

Not Installed:DFSNServer

Not Installed:DFSRInfrastructureServerEdition

Not Installed:DHCPServerCore

Not Installed:DNSServerCoreRole

Not Installed:FRSInfrastructure

Not Installed:IISWebServerRole

    |

    | Not Installed:IISFTPServer

    |        |

    |        | Not Installed:IISFTPExtensibility

    |        |

...

The names returned by OCList are same as the ones given by DISM.

Once you’ve identified the features you’d like, enable them using OCSetup:

C:\Users\Administrator>oclist |find «Cmdlets»

    |        | Not Installed:BestPracticesPSHCmdlets

    |        |     Installed:ServerManagerPSHCmdlets

C:\Users\Administrator>ocsetup BestPracticesPSHCmdlets

C:\Users\Administrator>oclist |find «Cmdlets»

    |        |     Installed:BestPracticesPSHCmdlets

    |        |     Installed:ServerManagerPSHCmdlets

Similar to DISM, OCSetup too is case sensitive and doesn’t automatically install dependent features. Moreover, it doesn’t give any output. To see whether the feature was enabled, you run OCList again and verify that it’s installed.

OCSetup has a much simpler syntax than DISM, but also doesn’t have the additional features that DISM has. Moreover, DISM is a useful tool to know for creating offline images for deploying on other machines, so it’s worth familiarizing oneself with DISM.

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

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
  • Папка \sources\SxS с установочного диска
  • Файл 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:\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

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

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

  • Ошибка 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.

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:\sources\install.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:\sources\install.wim:6

    Dism /image /RestoreHealth offline в windows 10

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

DISM is a command-line Microsoft tool for Windows 7/8/2008/2012. DISM stands for ‘Deployment Image Servicing and Management’. If you do a search for dism.exe you will find many posts of people using it to reduce the size of their WinSxS folder, especially after installing SP1. There is a 32-bit and a 64-bit version of this tool.

The actual command to do this cleanup is: dism.exe /online /cleanup-image /spsuperseded

So, you are sitting at the console of a Windows 2008 R2 x64 server, and you want to run this utility. Chances are, you will try to use the dism.exe that is listed inside the c:\Windows\SysWow64 folder.

However, if you do so, you may encounter the following error message: Error: 11 You cannot service a running 64-bit operating system with a 32-bit version of DISM. Please use the version of DISM that corresponds to your computer’s architecture.

In order to run this properly, you need to go directly to the native system folder to run this tool on a 64 bit system. Here are the steps:

  • Open command prompt window as administrator (‘Run as’).
  • Change directory by typing: cd \windows\system32
  • Run the command: dism.exe /online /cleanup-image /spsuperseded

This will take about ten minutes to run. Please note that even after the progress bar reaches 100.0%, the tool has not finished running. Do NOT close the command prompt window until you get the message “The operation completed successfully”.

What is the result of running this tool? I ran this on a Windows 2008 R2/SBS 2011 server, and it reduced the size of the WinSxS folder from 10.8GB to 7.37GB.

  

Not very drastic if you ask me. Not with today’s disk sizes. However, if you are running out of disk space on your server system drive, this might buy you some needed room!

First published on TechNet on May 13, 2014

It’s finally here! After pages and pages of comments from you requesting the ability to clean up the WinSxS directory and component store on Windows Server 2008 R2, an update is available.

http://support.microsoft.com/kb/2852386

As a refresher, the Windows Server 2008 R2 update is directly related to my previous blog post announcing a similar fix for Windows 7 client .

The Windows 7 version of this fix introduced an additional option to the Disk Cleanup wizard that would cleanup previous versions of Windows Update files. KB2852386 adds a Disk Cleanup option on Windows Server 2008 R2, similar to the Windows 7 update.

What does this mean for Windows Server 2008 R2? After installing this update and prior to being able to perform the cleanup, the Desktop Experience feature must be installed. Why you ask? Disk Cleanup is not installed by default on Windows Server 2008 R2. It is instead a component installed with the Desktop Experience feature.

Why was the update not included as a DISM switch like Windows Server 2012 R2?

This was evaluated, however, due to the amount of changes required and the rigorous change approval process, it was not feasible to back port the functionality this way. Knowing that it would be some time before everyone could upgrade to Windows Server 2012 R2 and based on feedback from an internal survey taken of a subset of enterprise customers, it was determined that this update would still be useful in its Disk Cleanup form, even with the Desktop Experience prerequisite. We hope you agree. However, we are aware that for some of you, the Desktop Experience requirement will be a deal breaker, but decided to release it anyway hoping it will help in some instances.

How can I get the update?

The update is available on Windows Update. It can also be manually downloaded from the Microsoft Update Catalog . The KB article listed above will also direct you to a download link in the Microsoft Download Center.

Let’s Cleanup those Old Windows Update Files!

First, let’s take a look at our starting point. Looking at my Windows 2008 R2 Server with SP1 installed, according to Windows Explorer, the size of my Windows/WinSxS directory is as follows:

The size of the WinSxS directory will vary by server. Some of you will have smaller WinSxS directories, some larger.

Installing the update is just like installing any other update. Just download and double-click on the .msu file:

Installing the update does not require Desktop Experience to be installed beforehand, but if you check your WinSxS directory again, you’ll see there has been no change to the size. This is expected as we need to run Disk Cleanup in order for this to take effect. It also does not require a reboot to install the hotfix.

But…we can’t do anything with what we just installed until we get Disk Cleanup which is installed with the Desktop Experience feature.

When installing Desktop Experience, it does require additional features. Select the button to Add Required Features and click Next and then Install:

A reboot is required to finalize the install.

Click Close and Reboot when prompted.

After we reboot, a Disk Cleanup option can be found under Start —> All Programs —> Accessories —> System Tools:

On launch, Disk Cleanup prompts for the drive you want to clean up:

After clicking Ok, a scan is performed:

Several options are provided for cleanup, including a new option for Windows Update Cleanup:

Just like the Windows 7 cleanup, mileage will vary. Also like Windows 7, the actual cleanup occurs during the next reboot. After the reboot, taking a look at the WinSxS directory, it has shrunk to the following:

Automation

My super knowledgeable scripting cohort Tom Moser wrote a PowerShell script that automates THE ENTIRE PROCESS. Can I get a cheer? Ok. So maybe it is a bit much to expect IT admins to cheer, but can I get an appreciative grunt?  The script certainly beats the alternative of doing this all manually.

You can find the script on the TechNet Script Center here:

http://gallery.technet.microsoft.com/scriptcenter/CleanMgrexeKB2852386-83d7a1ae

What does the script do?

In short, the script does the following:

1) Installs Desktop Experience, if not previously installed, and performs a reboot.

2) Sets the appropriate registry keys to automate the cleanup. The script will cleanup not only previous Windows Update files as well as Service Pack files.

3) The script then initiates the cleanup.

4) If Desktop Experience was not previously installed, the script uninstalls it.

5) Performs final reboot.

For more details, read below.

The script can be run from any directory on the server. It has two parameters: LogPath and a switch called NoReboot. LogPath will allow the user to specify a log location or if none is specified, by default, the script will create a log in the same directory from which the script was executed. NoReboot allows the user to suppress reboots, but will require manual reboots by an administrator.

Note : Make sure to check the log file to verify the process completed successfully and to verify there is no manual interaction required. If the script has completed successfully, the log will end with CleanMgr complete .

The script has several phases, using a registry key to keep track of progress. After initial run, it inserts itself as a scheduled task, which runs as local system. The final phase removes the task.

Depending on pending reboots, etc, we have found that this phase may generate a few reboots. Do not be concerned if the server reboots a few times.

Other Options

Aside from the cleanup mechanism included with this fix, if you have applied SP1 and have not cleaned up afterwards, I’d highly recommend doing so by running the following command from an administrative command prompt:

dism /online /cleanup-image /spsuperseded

or

If you have installed the Desktop Experience feature and thus have the Disk Cleanup utility, you can select the following option to do the same thing:

Specifying the /spsuperceded switch or choosing to remove service pack backup files will remove the ability to uninstall the service pack. If you haven’t done it before, it is certain to free up some space.

The Origins of this Update (Hint: Windows Server 2012 R2)

I’ve mentioned a couple of times that this is a back port. What does that mean? Well, it means that this functionality is already built into a later operating system. In this case, that operating system is Windows Server 2012 R2. Not only do we have several mechanisms to automatically cleanup previous versions of Windows Update files like this update does, we even have the ability to more accurately determine the size of the component store (aka the WinSxS directory).

The command to accurately determine the size of the component store on Windows Server 2012 R2 is as follows:

Dism.exe /Online /Cleanup-Image /AnalyzeComponentStore

Running this command analyzes the component store to determine the size and whether cleanup is recommended. Notice in the screen shot that it provides you with the Windows Explorer reported size and the actual size:

Notice that the component store is much smaller than Windows Server 2008 R2 right out of the gate? This isn’t because I’ve used Features on Demand to remove roles and features. It’s because by default in Windows Server 2012 R2, we compress all unused binaries. Another win for Windows Server 2012 R2!

Looking at the breakdown of the 5.12GB. We see that Shared with Windows accounts for 3.83GB of the 5.12GB. Shared with Windows refers to the size of the files that are hardlinked between the WinSxS directory and the Windows location of the file. Because these hardlinks appear to take up space, but don’t really, we can subtract them from our component store size. Therefore, the actual size of the component store is the total of Backups and Disabled Features plus Cache and Temporary Data or 1.28GB.

But back to our cleanup.

In the above screen shot, it’s stated that component store cleanup is recommended. We can manually cleanup the component store on Windows Server 2012 R2 by running the following command:

Dism.exe /online /Cleanup-Image /StartComponentCleanup

What does this do? When this runs, Windows cleans up the previous versions of the component that was updated. In other words, it is doing exactly what our update does for Windows Server 2008 R2 SP1. It removes previous versions of the files updated by Windows Updates.

After running /StartCompomentCleanup, upon analyzing the size again, we see it is as follows:

So no notable difference really. Largely because we’ve been running this cleanup all along. This same command is run every 30 days as a scheduled task with a time limit of 1 hour.

With the scheduled task however, the task will wait at least 30 days after an updated component has been installed before uninstalling the previous versions of the component. This scheduled task can be found in Task Scheduler under the Task Scheduler Library\Microsoft\Windows\Servicing\StartComponentCleanup directory:

More information on this can be found here: http://technet.microsoft.com/en-us/library/dn251565.aspx

If you’re in all out spring cleaning mode and want to perform super deep cleanup, you can use the /resetbase command with the /startcomponentcleanup to remove all superseded versions of every component in the component store:

Dism.exe /online /Cleanup-Image /StartComponentCleanup /ResetBase

This removes the ability to uninstall any updates applied until this point in time.

And don’t forget the ability to completely remove any role or feature which also reduces the size. Take a look at one of my earlier blogs for more details on Features on Demand: http://blogs.technet.com/b/askpfeplat/archive/2013/02/24/how-to-reduce-the-size-of-the-winsxs-directory-and-free-up-disk-space-on-windows-server-2012-using-features-on-demand.aspx

Here’s a handy table showing when we introduced the various different cleanup and WinSxS size reductions by operating system:

Operating System Compress Unused WinSxS Binaries Cleanup Previous Windows Update Files Automatically Clean Up Previous Windows Update Files Cleanup All Components Features on Demand
Windows Server 2008 R2   With KB2852386      
Windows Server 2012 With KB2821895 x x   x
Windows Server 2012 R2 x x x x x

Want more information on how all this works under the covers?

Check out the following series on the AskCore team blog for an in-depth look at servicing improvements on Windows Server 2012 R2:

What’s New in Windows Servicing: Part 1

What’s New in Windows Servicing: Reduction of Windows Footprint : Part 2

What’s New in Windows Servicing: Service Stack Improvements: Part 3

More on the Desktop Experience Feature

The Desktop Experience feature includes the following components and features:

* Windows Media Player

* Desktop themes

* Video for Windows (AVI support)

* Windows SideShow

* Windows Defender

* Disk Cleanup

* Sync Center

* Sound Recorder

* Character Map

* Snipping Tool

* Ink Support

Most of these are not automatically turned on with the exception of Windows Defender whose service is started after reboot. You’ll likely want to stop the service and disable it after reboot. Not all 3rd party anti-viruses conflict with Windows Defender, but there have been reports that some do.

~ Charity Shelbourne and Tom Moser, Spring cleaning servers since 1998

Update May 15th, 2014

We are aware of a method of copying in the appropriate Disk Cleanup/CleanMgr files into the appropriate location to avoid installing the Desktop Experience. If this were a tested and supported option, we certainly would have included these details in this post and definitely would have used this method to automate the cleanup. However, it was determined early on that this method would not be supported. If you decide to do this, do so at your own risk.

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

Поработав с Windows Server 2008 R2, можно заметить, что многие изменения никак нельзя классифицировать как небольшие или нарастающие. Так, после установки первой системы Server 2008 R2 я хотел автоматизировать добавление нескольких ролей и функций. Я обратился к Servermanagercmd и обновленной OCSetup, чтобы посмотреть, как они работают под R2, и получил сообщение: Servermanagercmd is deprecated, and is not guaranteed to be supported in future releases of. Версия Server 2008 R2 предлагает не один, а два новых инструмента командной строки для добавления, удаления и изменения ролей и функций: несколько команд PowerShell, для запуска которых необходим Microsoft.NET 3.5, и автономную команду DISM (Deployment Image Servicing and Management), для которой совсем не нужен .NET.

Роли и функции

Прежде всего, DISM показывает все возможные роли и функции, а также состояние, установлены они или нет, — почти так же, как это делала команда Servermanagercmd -Query. Для получения этого списка введите:

dism/online/get-features

DISM выдаст несколько экранов вывода, например:

Name: FaxServiceRole

State: Disabled

Feature Name: Printing-Server-Role

State: Enabled

Видно, что включена роль, которую DISM называет Printing-Server-Role; роль, которую Server 2008 R2 называет Print and Document Services в Server Manager; роль Fax Server выключена. Иногда трудно догадаться, какие имена в DISM соответствуют тем или иным функциям; до сих пор я не знаю, как преобразовывать имена Server-Manager в имена DISM. Чтобы установить роль Fax Server, вводим:

dism/online/enable-feature: FaxServiceRole

В отличие от команды Servermanagercmd, которая могла бы установить только одну роль или функцию на команду (пока вы не осилили довольно сложный язык XML, чтобы устанавливать несколько функций сразу), команда DISM позволяет устанавливать несколько ролей и функций с немного различающимся синтаксисом:

dism/online/enable-feature

/featurename: [featurename]/featurename: [featurename]

Например, чтобы установить службу факса и роль сервера DNS в одной команде, можно ввести

dism/online/enable-feature

/featurename: DNS-Server-Full-Role

/featurename: FaxServiceRole

Для того чтобы удалить одну или несколько функций с помощью DISM, надо просто заменить /enable-feature на /disable-feature.

Команда DISM контролирует функции в Windows 7. Например, если необходимо установить Windows без игр, можно просто ввести команду:

dism/online/disable-feature: InboxGames

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

Погрешности

Команда Servermanagercmd была неплохим инструментом, только непонятно, почему разработчики Microsoft встроили ее поверх .NET. Это не позволяло команде работать на Server Core и требовало наличия OCSetup, другого инструмента для настройки ролей и функций с помощью командной строки. Создатели DISM освободили ее от такой зависимости, поэтому DISM работает не только на Server 2008 R2 с графическим интерфейсом, но и на Server Core R2 и даже в среде Windows Preinstallation Environment (PE) 3.0.

Как видно, DISM предлагает много ценных возможностей, однако есть у нее и недостатки. Больше всего досаждает упорство в определенных случаях по поводу имен функций. Например, я ввел:

dism/online/disable-feature: inboxgames

DISM мне сообщает: Feature name inboxgames is unknown. Далее обработка данных по ситуации восходит к администрации Эйзенхауэра. Я не знаю C++, но все же знаю, что для строки с именем mystring я могу преобразовать строку к нижнему регистру следующим образом:

for (j=1; j =tolower (mystring [j]);

Я уже упомянул о недостаточной ясности наименований функций и соответствии их функциональности. Что такое BusScan-ScanServer? Ни Google, ни Bing не предлагает помощи, можно только догадываться, что речь идет о новой функции сервера, которая поддерживает централизованное сканирование. Даже в случае известных ролей, например DNS или DHCP, имена остаются загадкой: почему DNS имеет имя DNS-Server-Full-Role, а DHCP — это DHCPServer?

Как есть, без прикрас…

Несмотря на некоторые недостатки, возможность команды DISM добавлять и удалять функции Windows очень полезна для автоматизации развертывания сервера или настольного компьютера. Стоит потратить немного времени, чтобы побольше узнать об этом.

Марк Минаси (mark@minasi.com) — редактор Windows IT Pro, MCSE и автор книги Mastering Windows Server 2003 (издательство Sybex) 

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Chuwi hi 10 air windows 10
  • Как продлить срок активации windows
  • Как запустить корсары на windows 10
  • Формат рисунка учетной записи windows 7
  • Windows 10 pro размер на диске