Утилита очистки диска (Disk Cleanup) позволяет администратору быстро очистить системный диск Windows Server, удалив ненужные и временные файлы, в том числе очистить каталог WinSxS от файлов устаревших компонентов, которые остались после установки обновлений. Утилита Disk Cleanup (cleanmgr.exe) по умолчанию уже установлена в графической версии Windows Server 2016/2019 (Desktop Experience), однако в предыдущих версиях Windows Server (2012 R2/ 2012/ 2008 R2) утилита cleanmgr.exe по-умолчанию отсутствует.
Содержание:
- Очистка диска с помощью Disk Cleanup в Windows Server 2016
- Очистка диска с помощью cleanmgr.exe из командной строки
- Запуск cleanmgr в Windows Server 2012 R2/ 2008 R2 без установки Desktop Experience
- Использование Disk Cleanup в Windows Server Core
Очистка диска с помощью Disk Cleanup в Windows Server 2016
Чтобы очистить системный диск от ненужных файлов в Windows Server 2016 с помощью утилиты Disk Cleanup, нужно в File Explorer открыть свойства диска и нажать кнопку Disk Cleanup.
Также можно в поисковой строке набрать «disk cleanup» или cleanmgr.exe.
Выберите диск, который вы хотите очистить.
Дождитесь пока мастер очистки проверит ваш диск и найдет ненужные файлы, которые можно безболезненно удалить.
Вы можете выбрать компоненты, файлы которых можно удалить. Вам предлагается удалить следующие временные файлы:
- Setup Log Files
- Downloaded Program Files
- Temporary Internet Files
- Recycle Bin
- Temporary files
- Thumbnails
Чтобы удалить ненужные системные файлы нажмите на кнопку Clean up system files.
Дополнительно предлагается очистить:
- Устаревшие файлы Windows Defender
- System archived Windows Error Reporting (каталог C:\ProgramData\Microsoft\Windows\WER\ReportQueue)
- System queued Windows Error Reporting
- Device driver packages
- Windows Update Cleanup — при этом выполняется очистка хранилища компонентов в каталоге WinSxS. Удаляются старые версии компонентов, которые остались после установки обновленных версий.
Выберите нужные опции, при этом Disk Cleanup покажет количество места, которое освободится. Нажмите Ок и подтвердите удаление временных файлов.
Дождитесь, пока утилита cleanmgr.exe удалит ненужные файлы.
Очистка диска с помощью cleanmgr.exe из командной строки
Утилита
cleanmgr.exe
имеет различные параметры командной строки, которые позволяют использовать ее в различных сценариях автоматической очистки системного диска. Их можно использовать как в Windows Server, так и на рабочих станциях пользователей с Windows 10.
cleanmgr [/d driveletter] [/SAGESET:n | /SAGERUN:n | TUNEUP:n | /LOWDISK | /VERYLOWDISK | /SETUP | /AUTOCLEAN]
Ключ
/AUTOCLEAN
используется для очистки старых файлов, оставшихся после апгрейда билда Windows. Параметр
/SETUP
позволяет удалить файлы, оставшиеся от предыдущей версии Windows (если вы выполняли in-place upgrade).
Команда
cleanmgr /LOWDISK
– запускает графический интерфейс Disk Cleanup с уже выбранными параметрами очистки.
Команда
cleanmgr /VERYLOWDISK
выполняет автоматическую очистку, а после окончания оторажает информацией о выполненных действиях и свободном месте.
You have successfully resolved the low disk space condition. Your C:\ volume now has 10000 Mb of free space remaining.
С помощью параметров
/sageset:n
и
/sagerun:n
вы можете создать и выполнить настроенный набор параметров очистки.
Например, выполните команду
cleanmgr /sageset:11
. В открывшемся окне выберите компоненты и файлы, которые нужно автоматически очищать (я выбрал все опции).
Эти настройки сохраняются в ветке реестра HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches. В этой ветке перечислены все компоненты Windows, которые можно очистить с помощью Disk Cleanup. Для каждой опции, которую вы выбрали создается параметр типа DWORD с именем StateFlags0011 (
0011
это число, которое вы указали в параметре sageset).
Чтобы запустить процесс очистки с выбранными параметрами, выполните команду:
cleanmgr /sagerun:11
Если вам нужно настроить автоматическую очистку дисков на компьютерах (или серверах) в домене, вам достаточно экспортировать эту ветку реестра и распространить ее через GPO.
Для автоматического запуска очистки системного диска на рабочих станциях с Windows 10 можно создать задание в планировщике со следующим PowerShell скриптом:
Start-Process -FilePath CleanMgr.exe -ArgumentList '/sagerun:11' -WindowStyle Hidden -Wait
Запуск cleanmgr в Windows Server 2012 R2/ 2008 R2 без установки Desktop Experience
В Windows Server 2012 / R2 и 2008 /R2 по умолчанию не установлена утилита очистки диска Disk Cleanup (cleanmgr.exe). Чтобы воспользоваться утилитой cleanmgr сначала нужно установить отдельный компонент сервера Desktop Experience (Возможности рабочего стола) с помощью Server Manager или PowerShell (
Install-WindowsFeature Desktop-Experience
).
Но вместе с Desktop Experience устанавливается множество других компонентов, которые абсолютно не нужны на сервере:
- Windows Media Player
- Темы рабочего стола
- Поддержка AVI для Windows
- Windows SideShow
- Windows Defender
- Disk Cleanup
- Sync Center
- Запись звука
- Character Map
- Snipping Tool
Для запуска мастера очистки дисков в Windows Server можно воспользоваться более простым методом: достаточно скопировать в системный каталог два файла из каталога WinSxS: Cleanmgr.exe и Cleanmgr.exe.mui. Ниже представлены команды для копирования файлов cleanmgr из каталога WinSxS для разных версий Windows Server (во всех случаях используется путь для английских редакций ОC).
| ОС | Команда копирования файлов cleanmgr |
| Windows Server 2008 R2 x64 |
copy C:\Windows\winsxs\amd64_microsoft-windows-cleanmgr_31bf3856ad364e35_6.1.7600.16385_none_c9392808773cd7da\cleanmgr.exe C:\Windows\System32\
|
| Windows Server 2008 x64 |
copy C:\Windows\winsxs\amd64_microsoft-windows-cleanmgr_31bf3856ad364e35_6.0.6001.18000_none_c962d1e515e94269\cleanmgr.exe C:\Windows\System32\
|
| Windows Server 2012 x64 |
copy C:\Windows\WinSxS\amd64_microsoft-windows-cleanmgr_31bf3856ad364e35_6.2.9200.16384_none_c60dddc5e750072a\cleanmgr.exe C:\Windows\System32\
|
Windows Server 2012 R2 x64
Рассмотренный выше трюк не работает в Windows Server 2012 R2 из-за изменений, внесенных обновлением KB2821895. Дело в том, что после установки данного обновления для хранения бинарных файлов компонентов стала использоваться компрессия. При попытке запустить скопированный cleanmgr.exe появляется ошибка:
The Program or feature \??\C:\Windows\system32\cleanmgr.exe cannot start or run due to incompatibility with 64-bit version of Windows
В качестве обходного решения можно воспользоваться такой методикой:
- Установить компонент Windows Desktop Experience:
Install-WindowsFeature Desktop-Experience - Перезагрузить сервер;
- Скопировать файлы %windir%\system32\cleanmgr.exe и %windir%\system32\en-US\cleanmgr.exe.mui в произвольный каталог (c:\temp)
- Удалить компонент:
Uninstall-WindowsFeature Desktop-Experience - Перезагрузка;
- Скопировать файлы cleanmgr.exe и cleanmgr.exe.mui в указанные выше каталоги
В дальнейшем эти два файла можно скопировать и на все другие сервера или интегрировать в шаблоны виртуальных машин с Windows Server 2012 R2.
Ссылка на скачивание готового комплекта файлов cleanmgr.exe.mui + cleanmgr.exe для Windows Server 2012 R2 на ЯндексДиске (thks Alex Kornev).
Для запуска утилиты очистки диска теперь достаточно выполнять с правами администратора команду
cleanmgr.exe
.
Совет. Для очистки устаревших файлов компонентов, оставшихся после установки обновлений, в Windows Server R2 можно воспользоваться командой DISM:
dism.exe /online /Cleanup-Image /StartComponentCleanup /ResetBase
В Windows Server 2008 R2, чтобы cleanmgr могла удалять устаревшие файлы обновлений нужно установить отдельный патч KB2852386.
Использование Disk Cleanup в Windows Server Core
В Windows Server Core 2016, в котором отсутствует полноценный графический интерфейс, утилита Disk Cleanup также не установлена. Если вы хотите использовать cleanmgr.exe для очистки диска в Server Core, достаточно скопировать следующие файлы из каталога WinSXS:
copy C:\Windows\WinSxS\amd64_microsoft-windows-cleanmgr_31bf3856ad364e35_10.0.14393.0_none_9ab8a1dc743e759a\cleanmgr.exe C:\Windows\System32\
copy C:\Windows\WinSxS\amd64_microsoft-windows-cleanmgr.resources_31bf3856ad364e35_10.0.14393.0_en-us_8b4adb68af596a23\cleanmgr.exe.mui C:\Windows\System32\en-US\
C диск мало места на диске это общая проблема в Windows Server 2012 и R2. Чтобы решить эту проблему, сначала лучше освободить место на диске. Чтобы выполнить эту задачу, Windows Server 2012 имеет родной Очистка диска инструмент. Но в отличие от других версий, этот инструмент не включен по умолчанию. Вот почему многие люди оставляют отзывы, что Очистка диска отсутствует in Windows Server 2012 (r2). В этой статье рассказывается, как добавить, установить и включить очистку диска в Windows Server 2012 R2 и как запустить очистку диска через cleanmgr командовать в Server 2012 освободить дисковое пространство.
Содержание:
- О Windows Server 2012 Утилита очистки диска
- Как установить/включить очистку диска в Windows Server 2012
- Добавить/включить очистку диска в Server 2012 без перезагрузки
- Установите очистку диска на Server 2012 с возможностями рабочего стола
- Как запустить очистку диска в Server 2012 R2 с cleanmgr команду
О Windows Server 2012 Утилита очистки диска
То же самое с другими версиями, Windows Server 2012 система C: диск переполняется после запуска сервера в течение определенного периода времени. Одним из решений является очистка диска C, удаление ненужных и ненужных файлов, чтобы освободить место на диске. Для этого Microsoft предоставляет собственный Очистка диска утилита, которую можно запустить через cleanmgr команда или с мастером графического интерфейса.
Чтобы очистить диск C Server 2012 (R2), родная утилита очистки диска является первым выбором, поскольку она проста, быстра и способна безопасно удалить наиболее распространенные типы ненужных файлов. Существуют сторонние программы оптимизации, но родная утилита очистки достаточно безопасна и мощна. Не нужно бороться за 1 ГБ свободного места, но подвергайте сервер опасности.
Как я сказал в начале, очистка диска в Server 2012 (R2) есть активирован по умолчанию. Это причина, по которой некоторые люди сообщают, что очистка диска отсутствует в Server 2012 (R2), или получите сообщение об ошибке: Windows не могу найти ‘cleanmgr’. Убедитесь, что вы правильно ввели имя, а затем попробуйте еще раз..
Перед очисткой диска в Windows 2012, вам необходимо заранее установить или включить эту утилиту.
Как установить/включить очистку диска в Windows Server 2012 R2
Существует два варианта включить очистку диска в Server 2012 (R2): скопируйте файлы из WinSxS и установите с функцией Desktop Experience.
Это легко и быстро, копируя файлы в определенную папку, но в некоторых средах очистка диска не работает. После установки функции «Возможности рабочего стола» очистка диска становится полностью функциональной, но для завершения установки требуется перезагрузка. Кроме того, вместе с Desktop Experience на сервере будет установлено множество других ненужных компонентов, таких как:
- Windows медиа-плеер
- Темы рабочего стола
- Поддержка AVI для Windows
- Windows Сайдшоу
- Windows защитник
- Центр синхронизации
- аудиозапись
- Таблица символов
- Ножницы
Я представлю оба метода для включения очистки диска в Windows Server 2012 (R2) один за другим выберите тот, который соответствует вашим потребностям.
1. Добавить/включить очистку диска в Server 2012 без перезагрузки
Вам просто нужно скопировать два файла Cleanmgr.exe и Cleanmgr.exe.mui из WinSxS в системный каталог.
к Server 2012 R2, этот метод копирования недействителен, и вам необходимо установить Desktop Experience. Если вы не уверены в своей версии, просто нажмите Windows + R вместе на клавиатуре, чтобы начать Run, напишите WINVER и нажмите Enter Проверять.
Как включить очистку диска в Windows Server 2012 без перезагрузки:
Шаг 1: Press Windows + X вместе на клавиатуре и выберите Командная строка (Администратор)
Шаг 2: Скопируйте приведенную ниже команду, вставьте в окно командной строки и нажмите Enter выполнить.
копия C: \Windows\WinSxS\amd64_microsoft-windows-cleanmgr_31bf3856ad364e35_6.2.9200.16384_none_c60dddc5e750072a\cleanmgr.exe C:\Windows\ System32 \
Шаг 3: Скопируйте, вставьте и выполните вторую команду:
копия C: \Windows\WinSxS\amd64_microsoft-windows-cleanmgr.resources_31bf3856ad364e35_6.2.9200.16384_en-us_b6a01752226afbb3\cleanmgr.exe.mui C:\Windows\ System32 \ EN-US \
2. Установите программу очистки диска на Server 2012 (R2) с возможностями рабочего стола
Как я уже говорил выше, вы не можете включить очистку диска в Windows Server 2012 R2, просто скопировав файлы, вам необходимо выполнить следующие шаги, чтобы установить утилиту очистки диска с возможностями рабочего стола.
Как установить очистку диска в Windows Server 2012 R2:
Шаг 1: Нажмите Диспетчер серверов в нижнем левом углу, а затем выберите второй вариант «Добавить роли и функции«.
Шаг 2: Просто нажмите Следующая в следующих 4 окнах.
Шаг 3: Нажмите на треугольник, чтобы развернуть Пользовательский интерфейс и инфраструктура, а затем установите флажок напротив «Рабочий стол«.
Появится окно с просьбой добавить дополнительные функции, нажмите Добавить функции внизу
Шаг 4: Установите флажок напротив «Рабочий стол«еще раз, а затем нажмите Следующая. Затем нажмите Установите в следующем окне.
Шаг 5: Нажмите Закрыто по окончании требуется перезагрузка, чтобы завершить установку и вступить в силу.
Как запустить очистку диска в Windows Server 2012 и R2
Существуют два способа открыть Очистку диска в Windows Server 2012 (R2).
Вариант 1: пробег cleanmgr (действительно после копирования файлов и установки)
- Press Windows + R на клавиатуре введите cleanmgr и нажмите Enter.
- Выберите диск C: (или другой) в раскрывающемся списке и нажмите OK.
Вариант 2: через проводник (действует только после установки)
- Откройте проводник, щелкните правой кнопкой мыши диск C и выберите НЕДВИЖИМОСТИ
. - Нажмите Очистка диска Кнопка в этой середине.
Независимо от того, каким образом, очень легко освободить дисковое пространство с помощью Disk Cleanup в Windows Server 2012 (R2), просто установите флажок напротив файлов, которые вы хотите удалить, а затем нажмите OK выполнить.
Мой тестовый сервер установлен недавно, поэтому я могу освободить немного места. Серверам, которые никогда или давно не освобождали дисковое пространство, Server 2012 Утилита очистки диска может помочь вам восстановить несколько ГБ дискового пространства.
Как почистить диск в Windows Server 2012 (R2) с cleanmgr команду
Есть 3 способа запуска cleanmgr команду in Server 2012 (R2), выберите тот, который соответствует вашим потребностям.
① Все ненужные файлы выбираются и подтверждаются самостоятельно
- Press Windows и R вместе на клавиатуре.
- вход cleanmgr /LOWDISK и нажмите Enter.
- Появится диалоговое окно «Очистка диска» со всеми типами файлов, выбранных по умолчанию, поэтому вам просто нужно нажать «ОК» для подтверждения.
② Очистить все ненужные файлы автоматически
- Press Windows и R вместе на клавиатуре.
- вход cleanmgr /VERYLOWDISK и нажмите Enter.
Затем Очистка диска удалит ВСЕ ненужные файлы автоматически, а затем покажет вам диалоговое окно с результатом.
③ Очистить указанные ненужные файлы автоматически
- Press Windows и R вместе на клавиатуре, чтобы открыть Run.
- вход cleanmgr /sageset:1 и нажмите Enter. (Вы можете указать значение от 0 до 65535).
- Появится диалоговое окно «Очистка диска», выберите файлы для удаления и нажмите «ОК».
- В будущем вам просто нужно запустить cleanmgr /sageset:1 и нажмите Enter, предварительно выбранных ненужные файлы будут удалены автоматически. Если вы хотите удалить файлы разных типов, введите cleanmgr /sageset:2 на шаге 2 и запустить cleanmgr / Sageset: 2 на этапе 4.
Если у вас мало места при очистке диска в Windows Сервер 2012, или диск системы C создан маленький, вам лучше расширить диск C в больший размер. В противном случае диск C будет снова заполнен в ближайшее время. Фактически, даже если вы получите 10 ГБ свободного места, оно будет быстро уничтожено новыми сгенерированными ненужными файлами.
В программное обеспечение серверного раздела, вы можете сжать любой том данных на том же диске, чтобы получить нераспределенное пространство, а затем добавить его на диск C. Таким образом, на диске C будет больше свободного места. Операционная система, программы и все остальное остаются такими же, как и прежде. Этот шаг наиболее эффективен для решения этой проблемы.
Скачать NIUBI Partition Editor и следуйте инструкциям в видео, чтобы добавить больше свободного места на диске C.
Помимо сокращения и расширения разделов без потери данных, NIUBI Partition Editor помогает выполнять многие другие операции по управлению дисками и разделами.
Обновлено 30 октября 2024 г. в 3:16| Рекомендуемые
Обзор:
- Что такое очистка диска
- Очистка диска Windows Server 2012 отсутствует
- Включить очистку диска в Windows Server 2012
- Включить очистку диска Server 2012 без перезагрузки
- Установите очистку диска с помощью рабочего стола
- Важный шаг после очистки диска
Что такое очистка диска
Очистка диска (cleanmgr.exe) — это служебная программа для обслуживания компьютера, впервые представленная в Windows 98 и включенная во все последующие выпуски Windows. Он предназначен для освобождения места на диске путем удаления файлов, которые больше не нужны или которые можно безопасно удалить.
Существует целый ряд различных категорий файлов, на которые ориентируется очистка диска при выполнении начального анализа диска:
- Сжатие старых файлов
- Временные файлы Интернета
- Временные файлы Windows
- Загруженные файлы программ
- Корзина
- Удаление неиспользуемых приложений или дополнительных компонентов Windows
- Файлы журнала установки
- Автономные веб-страницы (кэшированные)
Приведенный выше список не является исчерпывающим.
Очистка диска отсутствует в Windows Server 2012
Windows Disk Cleanup — очень полезная утилита, и я использовал ее для освободить дисковое пространство с сервера 2003. Он помогает безопасно и легко удалить большую часть мусора и ненужных файлов. Многие люди отмечают, что Disk Cleanup отсутствует в Server 2012 R2.
Если вы попытаетесь запустить очистку диска в Server 2012 из команды «Выполнить с помощью», вы получите сообщение об ошибке: Windows не может найти cleanmgr. Убедитесь, что вы правильно ввели имя, а затем повторите попытку..
Это связано с тем, что очистка диска не включена в Server 2012 по умолчанию, перед ее запуском для освобождения места на диске необходимо включить или установить этот инструмент.
Включить очистку диска в Windows Server 2012
Есть два способа включить очистку диска в Windows Server 2012 (R2):
- Копировать файлы из WinSxS
- Установить Desktop Experience
Первый вариант простой и быстрый, но в некоторых средах Disk Cleanup не будет работать. Второй вариант гарантирует, что Disk Cleanup будет работать в любых условиях, но для завершения установки функции Desktop Experience требуется перезагрузка. Кроме того, вместе с Desktop Experience на сервере устанавливается много других ненужных компонентов, таких как:
- Windows Media Player
- Темы рабочего стола
- Поддержка AVI для Windows
- Windows SideShow
- Defender для Windows
- Центр синхронизации
- аудиозапись
- Таблица символов
- Ножницы
1. Включить очистку диска в Server 2012 без перезагрузки
Примечание: Этот метод недопустим для Server 2012 R2.
Все, что вам нужно сделать, это скопировать два файла Cleanmgr.exe и Cleanmgr.exe.mui из WinSxS в системный каталог, шаги:
1. Найдите файлы:
- C:\Windows\WinSxS\amd64_microsoft-windows-cleanmgr_31bf3856ad364e35_6.2.9200.16384_none_c60dddc5e750072a\cleanmgr.exe
- C:\Windows\WinSxS\amd64_microsoft-windows-cleanmgr.resources_31bf3856ad364e35_6.2.9200.16384_en-us_b6a01752226afbb3\cleanmgr.exe.mui
2. Переместить файлы:
- Копировать Cleanmgr.exe в % SystemRoot% \ System32
- Копировать Cleanmgr.exe.mui в % SystemRoot% \ System32 \ EN-US
Теперь вы можете запустить инструмент очистки диска, запустив Cleanmgr.exe из командной строки.
2. Установите очистку диска в Server 2012 (R2) с возможностями рабочего стола.
Шаг 1: нажмите Диспетчер серверов в левом нижнем углу нажмите второй вариант «Добавить роли и функции».
Шаг 2: нажмите Следующая пока не увидишь Особенности.
Шаг 3. Установите флажок напротив «Рабочий стол«И нажмите Следующая.
Шаг 4. В течение нескольких минут после завершения установки нажмите Закрыто.
Шаг 5: Перезагрузите сервер, чтобы завершить добавление функций.
После загрузки на рабочий стол, щелкнув правой кнопкой мыши диск C в проводнике, вы увидите «Очистка диска».
Как запустить очистку диска на сервере Windows 2012
Если вы установили Очистку диска на сервере Windows 2012, есть два способа запустить эту утилиту:
- Press Windows + R ключи вместе, введите cleanmgr и нажмите Enter.
- Press Windows + E Чтобы открыть проводник, щелкните правой кнопкой мыши диск C и выберите «Очистка диска».
Если вы включите очистку диска Server 2012, просто скопировав файлы, будет действителен только метод 1.
Независимо от того, какой метод вы используете, появится диалоговое окно, вам просто нужно выбрать файлы для удаления и подтвердить операцию.
Важный шаг после очистки диска
Очистка диска — хороший инструмент, который может помочь освободить место на диске, но в большинстве случаев вы не можете освободить большое количество свободного места. Таким образом, диск C вскоре снова заполнится. Чтобы полностью решить эту проблему, лучше добавить больше свободного места на диске C с других разделов.
Шаг 1: Скачать NIUBI Partition Editor, щелкните правой кнопкой мыши D: диск (смежный том за диском C) и выберите «Изменить размер / переместить объем».
Шаг 2: Во всплывающем окне перетащите оставил граница правота или введите сумму в поле «Незанятое пространство до».
Нажмите OK и обратно в главное окно, диск D уменьшается, а Нераспределенное пространство остается слева. Слева внизу добавлена новая ожидающая операция.
Шаг 3: Щелкните правой кнопкой мыши диск C: в NIUBI и запустите «Изменить размер/Переместить том», перетащите правую граница правота объединить это нераспределенное пространство.
Шаг 4: Добавлена вторая ожидающая операция, щелкните Применить в левом верхнем углу, чтобы вступить в силу.
В большинстве случаев на том же диске достаточно свободного места в других разделах, поэтому вы можете переместить свободное место на диск C. Таким образом, операционная система, программы и все остальное (кроме размера раздела) остаются такими же, как и раньше. Лучше, чем другие инструменты, NIUBI Partition Editor имеет технологии Virtual Mode, Cancel-at-well, 1-Second Rollback и Hot Clone для защиты системы и данных. Помимо сжатия и расширения раздела без потери данных, этот инструмент помогает вам выполнять множество других операций по управлению разделами диска.
Советы: вам лучше расширить диск C до максимально возможного размера с помощью NIUBI и ежемесячно запускать очистку диска в Windows Server 2012, чтобы удалить новые ненужные файлы.
Подробнее Скачать
The Disk Cleanup tool allows the administrator to quickly clean up the Windows Server system drive by deleting unnecessary and temporary files, including cleaning the WinSxS directory from files of outdated components that remained after installing the latest cumulative updates. The Disk Cleanup utility (cleanmgr.exe) is installed by default on the GUI editions of Windows Server 2016/2019 (Desktop Experience). However, in previous versions of Windows Server (2012 R2/2012/2008 R2), the cleanmgr.exe tool is missing.
Contents:
- Using Disk Cleanup Tool on Windows Server 2016
- Cleanmgr.exe: Disk Cleanup Command-Line Options
- How to Enable Disk Cleanup on Windows Server 2012 R2/2008 R2 without Installing Desktop Experience?
- Using Disk Cleanup on Windows Server Core Edition
Using Disk Cleanup Tool on Windows Server 2016
To clean the system disk from unneeded files on Windows Server 2016 using the Disk Cleanup utility, you need to open the disk properties in File Explorer and click the Disk Cleanup button.
You can also type the “disk cleanup” or cleanmgr.exe in the search box.
Select the drive you want to clean.
Wait until the cleaning wizard checks your disk and finds unnecessary files that can be safely deleted.
You can select components whose files can be deleted. You are prompted to delete the following temporary files:
- Setup Log Files;
- Downloaded Program Files;
- Temporary Internet Files;
- Recycle Bin;
- Temporary files;
- Thumbnails.
To remove unneeded system files, click on the Clean up system files button.
Additionally, it is proposed to clean up:
- Outdated Windows Defender files;
- System archived Windows Error Reporting files (the folder C:\ProgramData\Microsoft\Windows\WER\ReportQueue);
- System queued Windows Error Reporting;
- Device driver packages (see How to Remove Unused Drives from Driver Store);
- Windows Update Cleanup — this allows you to clean up the component store in the WinSxS directory. Old versions of components files that remain after installing updated ones are removed.
Select the options you need, and Disk Cleanup will show the amount of disk space you gave. Click OK and confirm the deletion of files.
Wait for the cleanmgr.exe tool to remove the unnecessary files.
Cleanmgr.exe: Disk Cleanup Command-Line Options
The cleanmgr.exe tool has several command-line options that allow it to be used in various automatic drive cleaning scenarios. They can be used both on Windows Server and on user desktop workstations running Windows 10.
cleanmgr.exe [/d driveletter] [/SAGESET:n | /SAGERUN:n | TUNEUP:n | /LOWDISK | /VERYLOWDISK | /SETUP | /AUTOCLEAN]
The /AUTOCLEAN parameter is used to delete old files left after upgrading a Windows build. The /SETUP option allows you to delete files left from a previous version of Windows (if you performed an in-place upgrade).
The cleanmgr /LOWDISK command runs the Disk Cleanup GUI with the already selected cleaning options.
The cleanmgr /VERYLOWDISK command performs automatic drive cleanup (without showing GUI), and after the end it displays information about the actions performed and available free space.
You have successfully resolved the low disk space condition. Your C:\ volume now has 10000 Mb of free space remaining.
Using the /sageset:xx and /sagerun:xx options, you can create and run a customized set of cleanup options.
For example, run the command: cleanmgr /sageset: 11. In the window that opens, select the components and files that you want to automatically cleanup (I selected all the options).
These settings are saved to the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches. This registry section lists all the Windows components that can be cleaned using the Disk Cleanup tool. For each option you select, a DWORD parameter is created with the name StateFlags0011 (0011 is the number you specified in the sageset parameter).
To start the drive cleanup task with the selected parameters, run the command:
cleanmgr /sagerun:11
If you need to configure automatic disk cleanup task on computers (or servers) in an Active Directory domain, you just need to export this registry key and deploy it on computers through the GPO.
To automatically cleanup the system drive on workstations with Windows 10, you can create a simple scheduled task with the following PowerShell code:
Start-Process -FilePath CleanMgr.exe -ArgumentList '/sagerun:11' -WindowStyle Hidden -Wait
How to Enable Disk Cleanup on Windows Server 2012 R2/2008 R2 without Installing Desktop Experience?
By default, in Windows Server 2012/R2 and 2008/R2 the Disk Cleanup (cleanmgr.exe) tool is not installed by default. To use the cleanmgr utility, first you have to install a separate server Desktop Experience feature using either Server Manager or PowerShell (Install-WindowsFeature Desktop-Experience).
Together with Desktop Experience, many other unnecessary components are installed on the server:
- Windows Media Player;
- Desktop themes;
- AVI support for Windows;
- Windows SideShow;
- Windows Defender Antivirus;
- Disk Cleanup;
- Sync Center;
- Audio recording;
- Character Map;
- Snipping Tool.
To run the Disk Cleanup on Windows Server, you can use a simple method: just copy two files Cleanmgr.exe and Cleanmgr.exe.mui from WinSxS to the system32 directory. Below you can see commands to copy cleanmgr files in different Windows versions (in all cases, the path is used for Windows Server English language editions).
| OS version | Command to copy cleanmgr bin files |
| Windows Server 2008 R2 x64 | copy C:\Windows\winsxs\amd64_microsoft-windows-cleanmgr_31bf3856ad364e35_6.1.7600.16385_none_c9392808773cd7da\cleanmgr.exe C:\Windows\System32\ |
| Windows Server 2008 x64 | copy C:\Windows\winsxs\amd64_microsoft-windows-cleanmgr_31bf3856ad364e35_6.0.6001.18000_none_c962d1e515e94269\cleanmgr.exe C:\Windows\System32\ |
| Windows Server 2012 x64 | copy C:\Windows\WinSxS\amd64_microsoft-windows-cleanmgr_31bf3856ad364e35_6.2.9200.16384_none_c60dddc5e750072a\cleanmgr.exe C:\Windows\System32\ |
Windows Server 2012 R2 x64
The trick described above doesn’t work on Windows Server 2012 R2 due to the changes made by KB2821895 update. The matter is that after you install this update, compression is used to store the binary component files. When you trying to run the copied cleanmgr.exe, the following error appears:
Unsupported 16-Bit Application The Program or feature \??\C:\Windows\system32\cleanmgr.exe cannot start or run due to incompatibility with 64-bit version of Windows.
As a workaround, you can use this method:
- Install Desktop Experience feature using PowerShell:
Install-WindowsFeature Desktop-Experience - Restart your server;
- Copy the files %windir%\system32\cleanmgr.exe and %windir%\system32\en-US\cleanmgr.exe.mui to any directory (c:\temp);
- Uninstall the feature:
Uninstall-WindowsFeature Desktop-Experience - Reboot;
- Copy the files cleanmgr.exe and cleanmgr.exe.mui to the directories mentioned above.
Later both of the files can be copied to other servers or integrated into your Windows Server 2012 R2 virtual machine template.
To start the Disk Cleanup tool, run the cleanmgr.exe command with the administrator privileges.
Tip. You can use the DISM command to delete outdated component files left after installing updates on Windows Server R2:
dism.exe /online /Cleanup-Image /StartComponentCleanup /ResetBase
To use cleanmgr.exe to delete old update files on Windows 2008 R2 / Windows 7 SP1, you need to install a separate patch KB2852386.
Using Disk Cleanup on Windows Server Core Edition
In Windows Server Core 2016, which lacks full-fledged GUI capabilities, Disk Cleanup tool is also not installed. If you want to use cleanmgr.exe to clean up the disk on Server Core, just copy the following files from the WinSXS directory:
copy C:\Windows\WinSxS\amd64_microsoft-windows-cleanmgr_31bf3856ad364e35_10.0.14393.0_none_9ab8a1dc743e759a\cleanmgr.exe C:\Windows\System32\copy C:\Windows\WinSxS\amd64_microsoft-windows-cleanmgr.resources_31bf3856ad364e35_10.0.14393.0_en-us_8b4adb68af596a23\cleanmgr.exe.mui C:\Windows\System32\en-US\
Over time, as your Windows Server runs longer, more and more disk space is eaten. Simply gone! Investigating the disk usage leaves you clueless; there are no large log files, crash dumps, or there is no software to be removed. Where did that space go?
The answer: Windows Updates, Service Pack, and hotfix installations.
The Windows disk cleanup utility cleanmgr is not available in Windows Server 2012 if the Desktop Experience-feature is not installed. This makes cleaning up used disk space a bit harder. You can utilize your cmd.exe or PowerShell command-line, and use Deployment Image Servicing and Management (DISM) to clean up the Windows Component Store (WinSxS) in Windows Server 2012 and up.
This post also shows you how to move the Windows Server SoftwareDistribution folder and user’s Documents folder to a different partition.
WinSxS cleanup in Windows Server — using DISM and PowerShell
The WinSxS folder is located in the Windows folder, for example C:\Windows\WinSxS. It’s the location for Windows Component Store files.
The Windows Component Store contains all the files that are required for a Windows installation. And, any updates to those files are also held within the component store as the updates are installed (source: KB 2795190 — and do read Manage the Component Store). The WinSxS folder will become large…
Let’s clean up WinSxS!
Regain used disk space with Deployment Image Servicing and Management (DISM)
Dism disk cleanup: Deployment Image Servicing and Management (DISM) is a command-line tool that allows you to install, uninstall, configure, and update Windows features, packages, drivers, and international settings. The /Cleanup-Image parameter of dism.exe provides advanced users more options to further reduce the size of the WinSxS folder.
The Dism.exe /Online /Cleanup-Image has a few extra parameters (or switches):
/AnalyzeComponentStore/StartComponentCleanup/ResetBasewith/StartComponentCleanup/SPSuperseded
Throughout this article, I assume you’ll read help options, just add /?, like: dism.exe /Online /Cleanup-Image /?.
If you enjoyed this, you might also enjoy the following post summing up 5 extra ways to clean up disk space in Windows Server!
Analyze WinSxS folder (Component Store) with /AnalyzeComponentStore
First you can use the /AnalyzeComponentStore parameter. This analyzes the size of the Component Store in Windows. The AnalyzeComponentStore option is available in Windows 8.1 Windows Server 2012 R2, and it’ll notify you whether a Component Store Cleanup is recommended or not.
& dism.exe /Online /Cleanup-Image /AnalyzeComponentStore
In the above image, AnalyzeComponentStore recommends a Component Store Cleanup. Let’s do so.
/StartComponentCleanup parameter
Dism.exe removes superseded and unused system files from a system with the /StartComponentCleanup parameter.
& dism.exe /Online /Cleanup-Image /StartComponentCleanup
There is also a registered scheduled task called StartComponentCleanup. You can start this task from the command line:
schtasks.exe /Run /TN "\Microsoft\Windows\Servicing\StartComponentCleanup"
The /StartComponentCleanup parameter is supported on Windows 8, Windows Server 2012 and up.
Using the /StartComponentCleanup parameter of Dism.exe on Windows 10 gives you similar results to running the StartComponentCleanup task in Task Scheduler, except previous versions of updated components will be immediately deleted (without a 30 day grace period) and you will not have a 1-hour timeout limitation.
From an elevated command prompt, type the following:
Dism.exe /online /Cleanup-Image /StartComponentCleanup
/ResetBase switch with /StartComponentCleanup parameter
Using the /ResetBase switch with the /StartComponentCleanup parameter of dism.exe, all superseded versions of every component in the component store is removed.
Dism.exe /Online /Cleanup-Image /StartComponentCleanup /ResetBase
All existing service packs and updates cannot be uninstalled after this command is completed. This will not block the uninstallation of future service packs or updates.
The /ResetBase parameter is supported on Windows 8.1 and Windows Server 2012 R2.
/SPSuperseded parameter
The /SPSuperseded parameter removes any backup components needed for de-installation of a service pack. The service pack cannot be uninstalled after this command is completed.
Dism.exe /Online /Cleanup-Image /SPSuperseded
The Service Pack cannot be uninstalled after this command is completed.
The /SPSuperseded parameter is supported on Windows 7 or Windows Server 2008 R2 Service Pack 1, 2012, 2012 R2.
The
/AnalyzeComponentStoreoption is available in Windows 8.1 and Windows Server 2012 R2. Use this to analyze the size of the Component Store (WinSxS folder) in Windows.
As said at the beginning of this article, the Disk Cleanup Tool is available in Windows Server 2012, if you install the Desktop Experience-feature.
In some versions of Windows Server, you can simply copy the Disk Cleanup Tool executable cleanmgr.exe and cleanmgr.exe.mui to C:\Windows\system32 and C:\Windows\system32\en-Us from an old Windows 2008 R2 server, if you don’t want to install the Desktop Experience feature.
The following steps to install (copy) cleanmgr may not work on all versions of Windows Server. Try for yourself.
Disk Cleanup Wizard addon on Windows Server 2008 R2
Microsoft KB2852386 adds a Disk Cleanup option on Windows Server 2008 R2, similar to the Windows 7 update. I’ve tested this on Windows Server 2012. It may not clean up everything, but at least a lot.
Here’s how to make cleanmgr.exe available on Windows Server 2012 Standard (Windows version 6.2.9200), without installing the Desktop Experience feature:
Microsoft Windows [Version 6.2.9200]
(c) 2012 Microsoft Corporation. All rights reserved.
PS C:\Users\jan> $osversion = [System.Environment]::OSVersion.Version
PS C:\Users\jan> write-host $osversion
6.2.9200.0
C:\Windows\System32>cd ..
C:\Windows>copy WinSxS\amd64_microsoft-windows-cleanmgr.resources_31bf3856ad364e35_6.2.9200.16384_en-us_b6a01752226afbb3\cleanmgr.exe.mui \Windows\system32\en-US
1 file(s) copied.
C:\Windows>copy WinSxS\amd64_microsoft-windows-cleanmgr_31bf3856ad364e35_6.2.9200.16384_none_c60dddc5e750072a\cleanmgr.exe \Windows\system32
1 file(s) copied.
C:\Windows>system32\cleanmgr.exe
C:\Windows>
Unfortunately, this no longer works on Windows Server 2012 R2 (6.3.9600), probably due to KB2821895. As Aaron pointed out in the comments, the above solution to copy over the cleanmgr.exe and cleanmgr.exe.mui files doesn’t always work well. Therefore I removed this information for Windows Server 2012 R2.
Fortunately, the Disk Cleanup functionality is back in Windows Server 2016 (at least TP5).
After cleaning up the disk, a server reboot is required. Don’t forget to reboot your computer — or server — afterwards! The actual cleanup of the WinSxs directory occurs during the next reboot.
Error 0x800f0906 with DISM /Online /Cleanup-Image, PowerShell Install-WindowsFeature and SFC /scannow
Some reports are available explaining Microsoft Security Bulletin MS14-046 broke DISM /Online /Cleanup-Image /RestoreHealth, PowerShell Install-WindowsFeature with -Source parameter, and SFC /scannow. Yes, it broke a lot…
An update is made available by Microsoft: KB3005628
Update for the .NET Framework 3.5 on Windows 8, Windows 8.1, Windows Server 2012, and Windows Server 2012 R2. This update resolves an issue that prevents the optional Microsoft .NET Framework 3.5 feature from being enabled after you install security update 2966827 or 2966828 (described in Microsoft Security Bulletin MS14-046) for the Microsoft .NET Framework 3.5.
Move Windows Server SoftwareDistribution folder
Over time, your Windows Updates SoftwareDistribution folder in c:\Windows\SoftwareDistribution can become quite large, for example when multiple updates were not installed successfully.
Windows Update files are downloaded to this folder and removed after successful installation. When you find yourself in a situation where your C: partition is rather small, and SoftwareDistribution folder eats up too much disk space, follow these steps to move the SoftwareDistribution folder to a different location.
All in a cmd.exe shell (Start > Run > cmd and press enter). In this example the new location is D:\Windows-SoftwareDistribution.
-
Stop the Windows Update service:
net stop wuauserv -
Rename the folder
c:\Windows\SoftwareDistributiontoc:\Windows\SoftwareDistribution.old:rename c:\windows\SoftwareDistribution SoftwareDistribution.old -
Create a link using Windows Sysinternals Junction, or Windows mklink
-
Create the new directory:
mkdir D:\Windows-SoftwareDistribution -
Create the Junction:
c:\>junction C:\Windows\SoftwareDistribution "D:\Windows-SoftwareDistribution", or:
c:\>mklink /J C:\Windows\SoftwareDistribution "D:\Windows-SoftwareDistribution"
-
-
Restart the Windows Update Service:
net start wuauserv
When, after a while, everything seems to run and update fine, you can delete your SoftwareDistribution.old folder safely.
Move User Documents folder
Another way for you to gain some extra free space is to move the User Documents folder (and others, like Downloads), for instance from C:\Users\$USER$\Documents to D:\User\$USER$\Documents (substitute \(USER\) with the username whose Documents folder you want to move). Here are the steps for you to follow (screenshots taken from Windows Server 2016 TP5):
- Open Explorer and right click on the Documents folder and then Properties
- Choose Location
- Change the location where files are stored
- When the destination does not exist, Windows asks to create the folder for you
- After completion, files are moved to their new location.
Conclusion
Yes, the Windows component store (WinSxS folder) can become large, very large. But fortunately, Microsoft provides us the tools to monitor, manage and clean up the WinSxS folder to regain that used disk space.
If you are comfortable with installing the Desktop Experience Windows feature on your system, you can have the Disk Cleanup utility on your system. Otherwise, you can use the DISM (Deployment Image Servicing and Management) command for various clean up tasks.
To gain some extra free space, you can also move the Windows SoftwareDistribution folder to a different partition.
