Очистка папки winsxs: чистим правильно разными способами

Папка "winsxs" - для чего она нужна и как ее чистить?

Запуск утилиты очистки диска в Windows Server 2012 R2 и 2008 без Desktop Experience

2019-01-12 · Posted in Windows Server 2008, Windows Server 2012

В Windows Server 2008 /R2 и 2012 / R2 по умолчанию не установлена утилита очистки диска — Disk Cleanup (cleanmgr.exe), позволяющая удалить ненужные файлы и очистить каталог WinSxS от файлов устаревших обновлений. Для ее запуска нужно  сначала установить отдельный компонент сервера 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. Ниже представлены команды для копирования файлов на разных версиях Windows (во всех случаях путь для английских редакций ОC)

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
copy C:\Windows\winsxs\amd64_microsoft-windows-cleanmgr.resources_31bf3856ad364e35_6.1.7600.16385_en-us_b9cb6194b257cc63\cleanmgr.exe.mui C:\Windows\System32\en-US

1
2

copyC\Windows\winsxs\amd64_microsoft-windows-cleanmgr_31bf3856ad364e35_6.1.7600.16385_none_c9392808773cd7da\cleanmgr.exeC\Windows\System32

copyC\Windows\winsxs\amd64_microsoft-windows-cleanmgr.resources_31bf3856ad364e35_6.1.7600.16385_en-us_b9cb6194b257cc63\cleanmgr.exe.muiC\Windows\System32\en-US

Windows Server 2008 x64

copy C:\Windows\winsxs\amd64_microsoft-windows-cleanmgr_31bf3856ad364e35_6.0.6001.18000_none_c962d1e515e94269\cleanmgr.exe C:\Windows\System32
copy C:Windows\winsxs\amd64_microsoft-windows-cleanmgr.resources_31bf3856ad364e35_6.0.6001.18000_en-us_b9f50b71510436f2\cleanmgr.exe.mui C:\Windows\System32\en-US

1
2

copyC\Windows\winsxs\amd64_microsoft-windows-cleanmgr_31bf3856ad364e35_6.0.6001.18000_none_c962d1e515e94269\cleanmgr.exeC\Windows\System32

copyCWindows\winsxs\amd64_microsoft-windows-cleanmgr.resources_31bf3856ad364e35_6.0.6001.18000_en-us_b9f50b71510436f2\cleanmgr.exe.muiC\Windows\System32\en-US

Windows Server 2012 x64

copy C:\Windows\WinSxS\amd64_microsoft-windows-cleanmgr_31bf3856ad364e35_6.2.9200.16384_none_c60dddc5e750072\acleanmgr.exe C:\Windows\System32
copy C:\Windows\WinSxS\amd64_microsoft-windows-cleanmgr.resources_31bf3856ad364e35_6.2.9200.16384_en-us_b6a01752226afbb3\cleanmgr.exe.mui C:\Windows\System32\en-US

1
2

copyC\Windows\WinSxS\amd64_microsoft-windows-cleanmgr_31bf3856ad364e35_6.2.9200.16384_none_c60dddc5e750072\acleanmgr.exeC\Windows\System32

copyC\Windows\WinSxS\amd64_microsoft-windows-cleanmgr.resources_31bf3856ad364e35_6.2.9200.16384_en-us_b6a01752226afbb3\cleanmgr.exe.muiC\Windows\System32\en-US

Для запуска утилиты очистки диска теперь достаточно выполнять с правами администратора команду cleanmgr.exe.

Windows Server 2012 R2 x64

Рассмотренный выше трюк не работает в Windows Server 2012 R2 из-за изменений, внесенных обновлением KB2821895. Дело в том, что после установки данного обновления для хранения бинарных файлов компонентов стала использоваться компрессия. При попытке запустить скопированный cleanmgr.exe появляется ошибка:
The Program or feature ??C:Windowssystem32cleanmgr.exe cannot start or run due to incompatibility with 64-bit version of windows

В качестве обходного решения можно воспользоваться такой методикой:

  1. Установить компонент Desktop Experience: Install-WindowsFeature Desktop-Experience
  2. Перезагрузить сервер
  3. Скопировать файлы %windir%system32cleanmgr.exe и %windir%system32en-UScleanmgr.exe.mui в произвольный каталог (c:temp)
  4. Удалить фичу: Uninstall-WindowsFeature Desktop-Experience
  5. Перезагрузка
  6. Скопировать файлы cleanmgr.exe и cleanmgr.exe.mui в описанные выше каталоги

В дальнейшем эти два файла можно скопировать и на все другие сервера или интегрировать в шаблоны виртуальных машин с Win 2012 R2.
Ссылка на скачивание готового комплекта файлов cleanmgr.exe.mui + cleanmgr.exe для Windows Server 2012 R2.

Вариант 4: Программы и компоненты

Помимо резервных копий обновлений в папке «WinSxS» также хранятся все компоненты Windows, включая их новые и старые версии и независимо от статуса активации. Уменьшить объем директории за счет компонентов можно с помощью консоли по аналогии с первым способом этой статьи.

  1. Снова откройте «Командную строку» или «Windows PowerShell».
  2. Если вы регулярно обновляете ОС, то помимо актуальных версий в папке «WinSxS» будут храниться старые копии компонентов. Чтобы их удалить, следует воспользоваться командой Dism.exe /online /Cleanup-Image /StartComponentCleanup /ResetBase.

    По завершении вы получите соответствующее уведомление. Объем же рассматриваемой директории должен будет значительно уменьшиться.

Эффективной такая команда будет, только если вы пользуетесь системными компонентами, предварительно отключив все ненужное. Развернуто о них было рассказано в другой нашей статье. В противном случае выполнение данной команды может практически не повлиять на размер папки «WinSxS».

Подробнее: Включение и отключение компонентов в Windows 10

Опишите, что у вас не получилось. Наши специалисты постараются ответить максимально быстро.

Как очистить папку WinSxS в Windows 7

Сразу предупредим, что обязательным условием является наличие установленного SP1 в системе. Дело в том, что 8 октября 2013 года Microsoft выпустила рекомендуемое обновление KB2852386 добавляющее возможность очистки данной папки. Установить его можно с помощью центра обновлений Windows или скачать пакет с помощью Internet Explorer с сайта Microsoft.

Если вам интересно, сколько реально освободится места, нужно сравнить свободное место на всем системном диске до и после очистки. Для этого щелкаем правой кнопкой мыши по системному диску в Проводнике и выбираем в меню пункт «Свойства». Запоминаем сколько свободно места на диске.

Теперь можно выполнить процедуру очистки папки WinSxS. Для этого нужно запустить утилиту очистки диска с административными правами. Есть два способа сделать это. Нажать кнопку «Очистка диска» на приведенным выше скриншоте, а затем в появившемся окне кнопку «Очистить системные файлы». Второй способ заключается в использование командной строки запущенной от имени администратора. Выполняете в ней команду cleanmgr. В появившемся окне выбираете системный диск и нажимаете «OK». Конечный результат обоих способов будет один и представлен на скриншоте ниже.

Снимаем галочки со всех чекбоксов кроме пункта «Очистка обновлений Windows» и жмем кнопку «OK». Будет произведена очистка папки WinSxS после завершения которой нужно обязательно перегрузиться. Когда система загрузится снова, можно опять вызвать свойства диска и посмотреть, сколько стало свободного места. Разница в показания до очистки и после позволяет узнать, сколько реально освободилось места на жестком диске компьютера.

Естественно папка WinSxS останется, а удалятся только старые версии файлов. Причем удаляются все версии кроме предпоследней. Отсюда следует вывод, что чудес ждать не следует, у некоторых может оказаться вообще удалять нечего, у кого то удалится несколько сотен мегабайт, но если система установлена давно и часто обновлялась то, скорее всего на несколько гигабайт можно рассчитывать. Кстати, в Windows 8 возможность очищать папку WinSxS от старых версий обновлений существует давно.

How to Check the Actual Size of WinSxS Folder on Windows 10?

The easiest way to get the current size of the WinSxS folder on Windows is to open the properties of the folder in File Explorer (or use a PowerShell script). But keep in mind that most file managers (including File Explorer) show a slightly larger WinSxS folder size than it takes on disk.

The fact is that the WinSxS directory contains a large number of hard links (symbolic links) to system files in other folders. File managers, when calculating the size of the WinSxS folder, take into account the size of files referenced by hard links, but this is not correct.

You can find out the real size of the WinSxS folder on disk using the du tool from Sysinternals:

You can also analyze the size of the component store (WinSxS folder) using the DISM command:

Deployment Image Servicing and Management tool

Component Store (WinSxS) information:
Windows Explorer Reported Size of Component Store : 8.44 GB
Actual Size of Component Store : 8.15 GB
Shared with Windows : 5. 74GB
Backups and Disabled Features : 1.97 GB
Cache and Temporary Data : 438.31 MB
Date of Last Cleanup : 2021-02-22 20:37:29
Number of Reclaimable Packages : 1
Component Store Cleanup Recommended : Yes
The operation completed successfully.

As you can see, in this case, I can reduce the size of the WinSxS folder by (1,97 + 0,44) Gb.

The DISM command also allows you to check and repair your Windows image:

Автоматическая очистка резервных копий обновлений в WinSxS

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

Для этого необходимо создать простую задачу StartComponentCleanup в MicrosoftWindowsServicing с нужной периодичностью выполнения.

Надеюсь, статья будет полезной и предостережет от нежелательных действий. В случае возникновения вопросов — задавайте, постараюсь ответить.

Информация к новости

17-11-2016

Категория: Чистка, оптимизация, твики / Программы

Привет админ! Неделю назад я стал замечать, что свободное пространство на моём диске (C:), с установленной Windows 10, стало куда-то исчезать, да и шутка ли, в один прекрасный день пропало целых 3 Гб. Далеко не сразу, но мне удалось найти виновника, а точнее виновницу, ей оказалась папка WinSxS — её размер в моей операционной системе ещё неделю назад был 15 Гб, но на сегодня он уже составляет 18 Гб. Также я заметил, после чего именно эта папка так сильно разрослась, причиной оказались — обновления операционной системы, за прошлую неделю моя Windows 10 получала их слишком много, ноутбук несколько раз просил меня перезагрузиться для установки обновлений. Вопрос мой такой. О папке WinSxS в интернете написано много, но всё-таки, каким образом безопаснее всего очистить эту папку или она когда-нибудь очистится сама? Какие именно компоненты системы хранит папка WinSxS? Говорят, что на деле она занимаетнамного меньше места, чем видно в её свойствах и находятся на ней всего лишь символические ссылки.

Remove Unused Roles and Features from Windows 10/Windows Server

Features on Demand on Windows allows to remove binary files of the unused roles from the WinSxS folder. You can remove roles and features binaries on Windows Server using the Uninstall-WindowsFeature PoweShell cmdlet.

Windows 10 does not have the Uninstall-WindowsFeature cmdlet, and you must use DISM.exe to remove features from the Windows image.

Note that DISM, unlike the PowerShell cmdlet, doesn’t remove dependent features.

A complete list of available features in Windows 10 image can be obtained using the command:

To remove, for example, the TelnetClient feature from the Windows image (from the WinSxS folder), run the command:

If you display the list of all on-demand features available in Windows, you will see that the component status has changed to Disabled with Payload Removed.

Thus, Windows allows to significantly reduce the size of the WinSxS folder by removing the unused components from the disk. The only thing is that this cleanup method suits only for the advanced users, who are familiar with the Windows 10 features and their purpose.

How to Enable NTFS Compress on WinSxS Folder on Windows 10?

Another way to reduce the size of the WinSxS directory on Windows 10 is to compress the directory contents on the level of the NTFS file system.

Note. As in case of any non-standard intervention into the system configuration, you are strongly recommended to create a full backup of your Windows 10 image.

  1. Open the command prompt as administrator;
  2. Stop and disable Windows Installer and Windows Module Installer services:
  3. Let’s backup the Access Control Lists (ACLs) assigned to the files and folders in the WinSxS directory using the built-in icacls tool. A backup copy of an ACL is a plain text file that lists all files and directories and the NTFS permissions assigned to them (later this file will be needed to restore the original ACLs):
  4. Assign yourself as an owner of the WinSxS folder and all its subfolders:
  5. Grant your account full control permissions on the WinSxS directory:
  6. You can now compress files in the WinSxS directory using the compact command. Because some of the files can be used by Windows, you need to specify the option. Otherwise, compression will stop at the first locked file (in Windows 10, you can use more advanced LZX compression):
  7. Restore the owner of the WinSxS directory back to TrustedInstaller:
  8. Restore the original ACLs for the WinSxS folder items using the ACL backup file you created earlier:
  9. Restore the default startup type for the Windows Installer and Windows Module Installer services:

Now check the current size of the WinSxS folder:

As you can see, in our example the size of the WinSxS folder after the compression has reduced from 9.4GB to 6.5GB (about a third). Not bad, especially for a small-sized SSD-drive.

These commands can either be run separately (then it is much easier to track the results of each of them) or used in a single script file. If you run it, the described compression procedure for items in the WinSxS folder will start. You can download the ready-to-use batch file to enable NTFS compression on WinSxS here: winsxs_ntfs_compress.bat

You can use this script regularly because new uncompressed files will appear in the WinSxS folder after you install new Windows updates or apps.

What can be affected by compressing the WinSxS folder? Windows works transparently with compressed files. However, when processing such files, it may take additional CPU time to decompress/compress them. This may cause a slight slowdown when installing Windows components or updates. However, on modern CPUs, the file compression/ decompression operations are performed almost instantly, so the user may not even notice the real impact on performance.

Clean Up the WinSxS Folder

This topic is about the different ways to reduce the size of the WinSxS folder on a running Windows 10, or later, installation.

Don’t delete the WinSxS folder, you can instead reduce the size of the WinSxS folder using tools built into Windows. For more information about the WinSxS folder, see Manage the Component Store.

The operating system automatically reduces the size of the WinSxS folder by using methods similar to the ones described in this topic. Windows also uses internal processes to reduce the size of the WinSxS folder, such as uninstalling and deleting packages with components that have been replaced by other components with newer versions. Previous versions of some components are kept on the system for a period of time, allowing you to rollback if necessary. After a period of time, these older components are automatically removed from the installation.

You can also reduce the size of a Windows image using some of the same techniques, as discussed in Reduce the Size of the Component Store in an Offline Windows Image.

To learn about finding the size of your WinSxS folder, see Determine the actual size of the WinSxS folder.

Deleting files from the WinSxS folder or deleting the entire WinSxS folder may severely damage your system so that your PC might not boot and make it impossible to update.

You have a number of ways to start the cleanup of the component store, which use a combination of package deletion and component compression to clean up the WinSxS folder:

Task Scheduler

The StartComponentCleanup task automatically cleans up components when the system isn’t in use. When run automatically, the task will wait at least 30 days after an updated component has been installed before uninstalling the previous versions of the component.

If you choose to run this task, the task will have a 1 hour timeout and may not completely clean up all files.

Run the StartComponentCleanup task in Task Scheduler to clean up and compress components

If Task Scheduler is not open, start the Task Scheduler. For more information, see Start Task Scheduler.

Expand the console tree and navigate to Task Scheduler Library\Microsoft\Windows\Servicing\StartComponentCleanup.

Under Selected Item, click Run

The StartComponentCleanup task can also be started from the command line.

Dism.exe

The /Cleanup-Image parameter of Dism.exe provides advanced users more options to further reduce the size of the WinSxS folder. For more information, see DISM Operating System Package Servicing Command-Line Options.

Use the /StartComponentCleanup parameter

Using the /StartComponentCleanup parameter of Dism.exe on a running version of Windows 10 or later 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, run:

Use the /ResetBase switch with the /StartComponentCleanup parameter

Using the /ResetBase parameter together with the /StartComponentCleanup parameter of DISM.exe on a running version of Windows 10 or later removes all superseded versions of every component in the component store.

From an elevated command prompt, run:

All existing update packages can’t be uninstalled after this command is completed, but this won’t block the uninstallation of future update packages.

Use the /SPSuperseded parameter

To reduce the amount of space used by a Service Pack, use the /SPSuperseded parameter of Dism.exe on a running version of Windows to remove any backup components needed for uninstallation of the service pack. A service pack is a collection of cumulative updates for a particular release of Windows.

From an elevated command prompt, run:

The service pack cannot be uninstalled after this command is completed.

You can use Disk Cleanup to reduce the number of unnecessary files on your drives, which can help your PC run faster. It can delete temporary files and system files, empty the Recycle Bin, and remove a variety of other items that you might no longer need. The option to cleanup updates helps reduce the size of the component store.

How to reduce size of WinSxS folder using Command Prompt

Checking WinSxS folder size

To determine the actual size of the WinSxS folder, 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 determine the size of the WinSxS folder and press Enter: dism /Online /Cleanup-Image /AnalyzeComponentStore

(Image credit: Future)

  1. Confirm the reported size of the component store to see how much space the WinSxS folder is taking.
  2. Check the «Component Store Cleanup Recommended» information to determine whether cleanup is necessary.

Once you complete the steps, you’ll be able to determine the size of the Windows Side by Side folder and whether cleanup is recommended.

In addition, the command will return other useful information, such as how much of the components are shared with Windows 10 as well as the size for backups and disabled features, and the last time you used the cleanup tool.

Cleaning up WinSxS folder

To reduce the size of the WinSxS folder using Command Prompt, 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 determine the size of the WinSxS folder and press Enter: dism /online /Cleanup-Image /StartComponentCleanup

(Image credit: Future)

After you complete the steps, the command will run to delete those components wasting space on the hard drive. However, once the WinSxS is clean, you won’t be able to roll back to a previous build until the next update.

If you want to determine how much space you have reclaimed using Command Prompt, you can re-run the command to analyze the folder and compare the «Actual Size of Component Store» values with the previous result.

Как очистить и сжать папку WinSxS в Windows 10

Если вы найдете папку WinSxS, то будете удивлены ее размерами. Находится она по такому пути — Этот компьютер > Локальный диск (C:) > Windows, и в нашем случае её размер составляет больше 8 ГБ.

Windows 10 использует системную папку WinSxS для хранения файлов, необходимых в процессе установки и функционирования системы, а так же резервных копий обновлений. И каждый раз, когда вы устанавливаете обновления, она многократно увеличивается в размере.

Как очистить папку WinSxS в Windows 10

Откройте командную строку от имени администратора, найдя ее через системный поиск.

Вставьте эту команду Dism.exe /online /cleanup-image /AnalyzeComponentStore и нажмите «Enter«. Произойдет анализ, и появится сообщение о необходимости очистки хранилища компонентов.

Для очистки, воспользуйтесь следующей командой Dism.exe /online /cleanup-image /StartComponentCleanup и дождитесь окончания операции.

Сжатие папки WinSxS

Для сжатия папки WinSxS скачайте и распакуйте этот архив, запустите от администратора файл LOWwinsxs.bat который выполнит процесс компрессии.

После выполнения всех процедур, нам удалось уменьшить размер папки WinSxS с восьми гигабайт до четырех.

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

Понравилась статья? Поделиться с друзьями:
Быть в курсе нового
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: