Takeown a r f c windows winsxs

Разработчики Microsoft, начиная с Win Vista решили сделать так, что все старые обновления системы (файлы компонентов и библиотеки), не удаляются, а остаются в системе.

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

Папка WinSxS расположенная по адресу C:\Windows\winsxs. Это служебная папка операционной системы Windows.

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

Хотим предупредить, что попытка удалить часть содержимого папки WinSxS в ручную, или с помощью программ, практически наверняка приведет к ошибкам в работе операционной системы,  или кполной потере работоспособности. Несколько способов корректной очистки этой папки будет рассмотрено ниже.

Способ 1

Безопасный, используются встроенные возможности Win, в принципе мы будем её сжимать.

1.       Запустите командную строку от имени администратора. Для этого, в строке поиска менюПусквведите команду:cmd.

Вводите поочередно указанные ниже команды, нажимая после ввода каждой из нихEnter

2.       Перейдите в папку Windows.cd /d C:\Windows

3.       Остановите службы «Установщик Windows» (msiserver) и «Установщик модулей Windows» (TrustedInstaller) и измените для них тип запуска: 

sc stop msiserver sc stop TrustedInstaller

sc config msiserver start= demand

sc config TrustedInstaller start= demand

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

icacls «winsxs» /save «C:\winsxs.acl» /t

5.       Установите себя в качестве владельца папкиWinSxS.

takeown /f «winsxs» /r

6.       Установите для себя права полного доступа к папкеWinSxS.

icacls «winsxs» /grant «%USERDOMAIN%\%USERNAME%»:(F) /t

7.       Сожмите папкуWinSxSсредствами системы.

compact /s:»winsxs» /c /a /i *

8.       Восстановите TrustedInstaller в качестве владельца папкиWinSxS.

icacls «winsxs» /setowner «NT SERVICE\TrustedInstaller» /t

9.       Восстановите из ранее сохраненного файла права доступа к папкеWinSxS.

icacls . /restore «C:\winsxs.acl»

 Данный способ не особо результативный способ, но безопасный.

Способ 2

Очень жестокий и коварный, но очень результативный!

заранее сделайтеBackup.

Все работы делаются под учетной записью «Администратор«

Нахождение в группе «Администраторы» не дадут полных прав!

Используется утилитаwinsxslite v1.88.7z

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

  1. Щелкните правой кнопкой мыши на файлWinsxsLite.batи выберите пунктЗапуск от имени администратора.
  2. Введитеqи нажмитеEnterдля создания файла конфигурации и выхода из программы.
  3. Повторно запустите файлWinsxsLite.batот имени администратора.
  4. Введите1и нажмитеEnterдля выбора действий, относящихся к первой фазе работы скрипта.
  5. Введитеsи нажмите Enterдля начала сканирования. По результатам сканирования будет создан файлToDo1.txt, содержащий лист файлов, которые должны быть заменены жесткими ссылками на более новые их версии.
  6. Введите1и нажмитеEnterдля выбора действий, относящихся к первой фазе работы скрипта.
  7. Введитеaи нажмитеEnterдля применения результатов сканирования в дальнейшей работе скрипта.
  8. Введитеqи нажмитеEnterдля выхода из программы.
  9. Перезагрузите компьютер.
  10. Повторно запустите файлWinsxsLite.batот имени администратора.
  11. Введите2и нажмитеEnterдля выбора действий, относящихся к второй фазе работы скрипта.
  12. Введитеsи нажмитеEnterдля начала сканирования. По результатам сканирования на основе выбранных языковых приоритетов, будет создан файлToDo2.txt, содержащий лист файлов, которые должны быть заменены жесткими ссылками на их английскую версию.
  13. Введите2и нажмитеEnterдля выбора действий, относящихся к второй фазе работы скрипта.
  14. Введитеaи нажмитеEnterдля применения результатов сканирования в дальнейшей работе скрипта.
    Незамененными на жесткие ссылки останутся только те языковые версии файлов, которые были добавлены Вами на первом шаге данной инструкции. По умолчанию — это русские языковые версии файлов.
  15. Введитеqи нажмитеEnterдля выхода из программы.
  16. Перезагрузите компьютер.
  17. Повторно запустите файлWinsxsLite.batот имени администратора.
  18. Введитеqи нажмитеEnterдля выхода из программы.

Frontol 6 ReleasePack 1 Год

Купить

In this article we will talk about the WinSxS folder in Windows, the reasons for its constant growth, and ways to clean up it. The C:\Windows\WinSxS directory is the repository of Windows components. This directory contains DLLs, binary, and XML files necessary for the installation and operation of various Windows roles or features. When installing the Windows updates (usually this happens every month), the new version of the updated component is installed on the system, while the old one is saved to the WinSxS folder (it is necessary to provide compatibility and make it possible to rollback to the previous versions of the components when you uninstall the Windows update).

The WinSxS directory has grown in size over time. Moreover, its size is not limited by anything (although in practice the size of the WinSxS folder in Windows 10 rarely exceeds 15-20 GB).

list of files in winsxs on windows 10

Contents:

  • How to Check the Actual Size of WinSxS Folder on Windows 10?
  • How to Clean Up the Component Store (WinSxS folder) on Windows?
  • Remove Unused Roles and Features from Windows 10/Windows Server
  • How to Enable NTFS Compress on WinSxS Folder on Windows 10?

In this article, we’ll go over the safest ways to clean up the WinSxS folder on Windows 10 and Windows Server 2016/2019:

  • Optimize the component store and remove old versions of Windows component files left after installing Windows updates;
  • Features on Demand – allows you to remove unused Windows components from the disk;
  • Enable NTFS compression on the WinSxS folder – a way to reduce the size of the WinSxS directory using the built-in compression of the NTFS file system.

Many users often ask: if it’s possible to manually delete files from the WinSxS folder. The answer is categorically NO! These actions can damage your Windows image. Though some attempts to remove files from the WinSxS folder can be successful, this method cannot be recommended.

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 %windir%\WinSxS 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:
du -v c:\windows\winSXS

how to check the real size of winsxs folder using du tool

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

Dism.exe /Online /Cleanup-Image /AnalyzeComponentStore

dism analyze component store - reporting winsxs folder real size

Deployment Image Servicing and Management tool
[==========================100.0%==========================]
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.

How to Clean Up the Component Store (WinSxS folder) on Windows?

The fastest and easiest way to clear the Windows Component Store (the WinSxS folder) is to optimize the storage with the command:

Dism.exe /Online /Cleanup-Image /StartComponentCleanup

clenup winsxs component store with Dism StartComponentCleanup

The StartComponentCleanup DISM option is supported on all Windows versions starting from Windows 8 and Windows Server 2012.

After cleaning is complete, check the current size of the component store:

Dism.exe /Online /Cleanup-Image /AnalyzeComponentStore

In my example, this reduced the size of the WinSxS folder by 2.4 GB.

The /StartComponentCleanup option has an additional /ResetBase option that allows you to remove all previous versions of components left after installing Windows updates. After that, you won’t be able to remove installed updates or Service Packs, and the Uninstall button will disappear from the Uninstall an Update Control Panel item). To clean up old versions of components, run:

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

In Windows 7 and Windows Server 2008 R2, an additional DISM option was used to clean up old versions of components that were left over after installing service packs.

DISM /online /Cleanup-Image /spsuperseded

You can also remove old update files using the “Disk Cleanup” wizard:

  1. Run the cleanmgr command as an administrator;
  2. Select the disk and in the next window, click the “Clean up system files” button;
  3. Then select the “Windows update cleanup” option. The Disk Cleanup tool will show how much space you can free up by deleting old Windows update files. In my example, this is 324 MB. Click OK to start the cleanup.

After you finish cleaning up the component store using DISM, check how much disk space has been freed.
In addition, Windows 10/Windows Server 2016 Task Scheduler has a special automatic maintenance task that regularly optimizes and cleans up the WinSxS folder (same operation as DISM with StartComponentCleanup parameter). This StartComponentCleanup task is located under the \Microsoft\Windows\Servicing section of the taskschd.msc. This task runs in the background and automatically removes component versions older than 30 days that have been superseded by newer files.

You can start this task manually like this:

schtasks.exe /Run /TN "\Microsoft\Windows\Servicing\StartComponentCleanup"

StartComponentCleanup task

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 role and feature binaries on Windows Server using the Uninstall-WindowsFeature PowerShell 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 Uninstall-WindowsFeature PowerShell cmdlet doesn’t remove dependent features.

A complete list of available features in Windows 10 image can be obtained using the command:
DISM.exe /Online /English /Get-Features /Format:Table

DISM Get-Features list

To remove, for example, the TelnetClient feature from the Windows image (from the WinSxS folder), run the command:
DISM.exe /Online /Disable-Feature /Featurename:TelnetClient /Remove

DISM Disable Feature Remove

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 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:
    sc stop msiserver
    sc stop TrustedInstaller
    sc config msiserver start= disabled
    sc config TrustedInstaller start= disabled
  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):
    icacls "%WINDIR%\WinSxS" /save "%WINDIR%\WinSxS_NTFS.acl" /t
    backup ntfs permissions of winsxs folder files using icacls

  4. Assign yourself as an owner of the WinSxS folder and all its subfolders:
    takeown /f "%WINDIR%\WinSxS" /r
  5. Grant your account full control permissions on the WinSxS directory:
    icacls "%WINDIR%\WinSxS" /grant "%USERDOMAIN%\%USERNAME%":(F) /t
  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 /i option. Otherwise, compression will stop at the first locked file (in Windows 10, you can use more advanced LZX compression):
    compact /s:"%WINDIR%\WinSxS" /c /a /i *
    compressing files in the winsxs folder using the compact.exe tool

  7. Restore the owner of the WinSxS directory back to TrustedInstaller:
    icacls "%WINDIR%\WinSxS" /setowner "NT SERVICE\TrustedInstaller" /t
  8. Restore the original ACLs for the WinSxS folder items using the ACL backup file you created earlier:
    icacls "%WINDIR%" /restore "%WINDIR%\WinSxS_NTFS.acl"
  9. Restore the default startup type for the Windows Installer and Windows Module Installer services:
    sc config msiserver start= demand
    sc config TrustedInstaller start= demand

Now check the current size of the WinSxS folder:

how to saves pace on winsxs folder on windows 10?

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.

В этой статье мы поговорим о каталоге WinSxS в Windows, причинах его постоянного роста и способах очистки. Каталог C:\windows\WinSxS является хранилищем компонентов Windows. В этом каталоге хранятся dll библиотеки, бинарные и xml файлы, необходимые для установки и работы различных ролей и компонентов Windows. Каждый раз когда вы устанавливаете обновления Windows (это происходит ежемесячно), новая версия обновляемого компонента устанавливается в систему, а старая сохраняется в хранилище компонентов WinSxS (это необходимо для обеспечения совместимости и возможности “отката“ к старым версиям компонентов при удалении проблемного обновления).

Со временем размер каталога WinSxS постоянно увеличивается. Причем его размер ничем не ограничен (хотя на практике размер папки WinSxS в Windows 10 редко превышает 15-20 Гб.)

каталог WinSxS в windows10

В этой статье мы рассмотрим наиболее безвредные способы очистки папки WinSxS в Windows 10 и Windows Server.

  • Оптимизация хранилища компонентов и удаление старых версий компонентов, оставшихся после установки обновлений Windows;
  • Технология Features on Demand (функции по требованию), позволяющая удалить неиспользуемые компоненты Windows с диска;
  • Сжатие файлов в папке WinSxS – способ уменьшить размер каталога WinSxS за счет включения NTFS компрессии.

У многих пользователей возникает естественный вопрос можно ли вручную удалить файлы из папки WinSxS. Ответ на этот вопрос – категоричное НЕТ! Такими действиями с большой долей вероятности вы сломаете свою Windows. И хотя отдельные попытки удаления конкретных файлов из папки WinSxS могут быть удачными, рекомендовать этот способ нельзя.

Содержание:

  • Как узнать реальный размер папки WinSxS в Windows 10?
  • Очистка хранилища компонентов WinSxS в Windows
  • Удаление неиспользуемых компонентов Windows (Windows Server)
  • Включаем NTFS сжатие на папке WinSxS в Windows

Как узнать реальный размер папки WinSxS в Windows 10?

Самый простой способ получить текущий размер каталога WinSxS в Windows, запустить проводник File Explorer и открыть свойства папки %windir%\WinSxS (или воспользоваться скриптом PowerShell). Но имейте в виду, что большинство файловых менеджеров (в том числе File Explorer) показывают несколько больший размер каталога WinSxS, чем он занимает на диске.

Дело в том, что в каталоге WinSxS есть большое количество hard links (жестких символических ссылок) на файлы в других системных каталогах. Файловые менеджеры при подсчете размера папки WinSxS учитывают объем файлов, на которые ссылаются жесткие ссылки, а это не корректно.

Чтобы реальный (без учета жестких ссылок) размер папки WinSxS, воспользуйтесь утилитой SysInternal du:

du -v c:\windows\winSXS

получить реальный размер каталога winsxs с помощью утилиты du.exe

Но проще всего проанализировать размер хранилища компонентов в папке WinSxS с помощью команды DISM:

Dism.exe /Online /Cleanup-Image /AnalyzeComponentStore

Dism.exe Cleanup Image-AnalyzeComponentStore

Разберемся, что возвращает данная команда:

Размер хранилища компонентов по данным проводника : 5.70 GB (это размер хранилища с учета жестких ссылок, который отображается в проводнике)
Фактический размер хранилища компонентов : 5.49 GB (реальный размер хранилища компонентов за исключением жестких ссылок)
Совместно с Windows : 3.12 GB (обязательные файлы системы, не могут быть удалены)
Резервные копии и отключенные компоненты : 2.12 GB (устаревшие файлы компонентов, которые нужны на случай проблем с установленными обновлениями)
Кэш и временные данные : 245.87 MB (файлы используются для ускорения работы системы обслуживания)
Дата последней очистки : 2018-07-31 12:45:23
Число освобождаемых пакетов : 10 (файлы, которые обновились после установки обновлений Windows, они будут удалены при очистке хранилища)
Рекомендуется очистка хранилища компонентов : Да

Как вы видите, в данном случае можно уменьшить размер каталога WinSxS на 2.1 Гб + 250 Мб.

Очистка хранилища компонентов WinSxS в Windows

Самый быстрый и простой способ освободить место в хранилище компонентов Windows (т.е. очистить папку WinSxS) – оптимизация хранилища командой:

Dism.exe /Online /Cleanup-Image /StartComponentCleanup

Dism.exe Cleanup Image StartComponentCleanup

Опция Dism /StartComponentCleanup поддерживается во всех версиях Windows, начиная с Windows 8/Windows Server.

После окончания очистки проверьте текущий размер хранилища компонентов:

Dism.exe /Online /Cleanup-Image /AnalyzeComponentStore

В моем примере это помогло уменьшить размер папки WinSxS на 2,5 Гб.

С помощью еще одного параметра /ResetBase вы можете удалить все предыдущие версии компонентов, оставшиеся после установки обновлений Windows. После этого вы не сможете удалить установленные обновления или Service Pack, а в панели обновлений
appwiz.cpl
у обновлений пропадет кнопка «Удалить»).

Чтобы очистить старые версии компонентов, выполните:

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

В Windows 7 и Windows Server 2008 R2 для очистки старых версий компонентов, оставшихся после установки сервис пака, использовался еще один параметр DISM:

dism /online /Cleanup-Image /spsuperseded

Также вы можете удалить устаревшие обновления с помощью мастера очистки диска. Выполните команду cleanmgr c правами администратора.

В окне утилиты выберите диск и в следующем окне нажмите кнопку «Очистить системны файлы».

Далее выберите опцию “Файлы журнала обновления Windows» и нажмите ОK. Утилита очистки диска покажет сколько места вы можете освободить, удалив файлы журнала старых обновлений Windows. В моем примере это 427 Мб.

После окончания очистки хранилища с помощью DISM проверьте сколько освободилось места на диске.

В планировщике задания Windows 10 и Windows Server 2016 есть специальное задание автоматического обслуживания, которое регулярно выполняет оптимизацию и очистку каталога WinSxS (выполняется действия, аналогичные команде dism с ключом StartComponentCleanup). Это задание StartComponentCleanup находится в разделе \Microsoft\Windows\Servicing. Данное задание запускается в фоновом режиме и автоматически удаляет версии компонентов старше 30 дней, которое были заменены более новыми версиями.

Можно запустить это задание вручную так:

schtasks.exe /Run /TN "\Microsoft\Windows\Servicing\StartComponentCleanup"

задание планировщика StartComponentCleanup - очистка компонентов

Удаление неиспользуемых компонентов Windows (Windows Server)

В статье Безопасная очистка папки WinSxS в Windows Server 2016/2012 мы рассмотрели функцию Features on Demand (функции по требованию), предоставляющую возможность удаления с диска бинарных файлов неиспользуемых ролей и компонентов из каталога WinSxS. Для этого в Windows Server используется командлет PoweShell Uninstall-WindowsFeature.

В Windows 10 командлет Uninstall-WindowsFeature отсуствует, и для удаления компонентов Windows из образа нужно использовать DISM.

DISM в отличии от Uninstall-WindowsFeature не удаляет зависимые компоненты.

Полный список доступных функций в образе Windows 10 можно получить с помощью команды:
DISM.exe /Online /English /Get-Features /Format:Table

windows 10 dism get-features список установленных компонентов

Чтобы удалить, например компонент TelnetClient с диска (из каталога WinSxS), выполните команду:
DISM.exe /Online /Disable-Feature /Featurename:TelnetClient /Remove

DISM Disable-Feature Remove

Если еще раз вывести список всех доступных функций по требованию в Windows, вы увидите, что статус компонента изменится на Disabled with Payload Removed.

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

Включаем NTFS сжатие на папке WinSxS в Windows

Еще один способ уменьшить размера каталога WinSxS в Windows 10 – сжать содержимое каталога на уровне файловой системы NTFS.

  1. Откройте командную строку с правами администратора;
  2. Остановите и отключите службы Windows Installer и Windows Module Installer:
    sc stop msiserver
    
    sc stop TrustedInstaller
    
    sc config msiserver start= disabled
    
    sc config TrustedInstaller start= disabled
  3. Создайте резервную копию списков доступа (ACL) назначенных на файлы и папки в каталоге WinSxS с помощью утилиты icacls. Резервная копия ACL представляет собой обычной текстовый файл, в котором указаны все файлы и каталоги и назначенные на них NTFS разрешения (в дальнейшем этот файл понадобиться для восстановления оригинальных ACL):
    icacls "%WINDIR%\WinSxS" /save "%WINDIR%\WinSxS_NTFS.acl" /t

    создаем резевную копию разрешений каталога winsxs

  4. Назначьте себя владельцем папки WinSxS и всех вложенных каталогов:
    takeown /f "%WINDIR%\WinSxS" /r
  5. Предоставьте своей учетной записи полные права на каталог WinSxS:
    icacls "%WINDIR%\WinSxS" /grant "%USERDOMAIN%\%USERNAME%":(F) /t
  6. Теперь можно выполнить сжатие файлов в каталоге WinSxS с помощью команды compact. Т.к. часть файлов может использоваться Windows, нужно указать параметр /i. Иначе сжатие будет остановлено на первом же занятом файле (в Windows 10 можно использовать более прогрессивное LZX сжатие):
    compact /s:"%WINDIR%\WinSxS" /c /a /i *

    Сжимаем содержимое каталога winsxs

  7. Теперь нужно восстановить TrustedInstaller как владельца каталога WinSxS:
    icacls "%WINDIR%\WinSxS" /setowner "NT SERVICE\TrustedInstaller" /t
  8. И вернуть оригинальные NTFS разрешения на каталог WinSxS из резервной копии ACL:
    icacls "%WINDIR%" /restore "%WINDIR%\WinSxS_NTFS.acl"
  9. Измените типа тип запуска служб Windows Installer и Windows Module Installer:
    sc config msiserver start= demand
    
    sc config TrustedInstaller start= demand

Проверьте текущий размер каталога WinSxS.

уменьшить размер каталога winsxs в windows10 с помощью сжатия

Как вы видите, в нашем примере размер папки WinSxS за счет сжатия уменьшился с 9,36 Гб до 6,5 Гб (примерно на треть). Неплохо, особо для небольшого по размеру SSD-диска.

Указанные команды можно выполнять по отдельности (так проще контролировать успешность выполнения каждой из них), либо можно объединить все операции в один файл скрипт. Вы можете скачать готовый bat файл для сжатия WinSxS здесь compress_winsxs.bat

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

На что может повлиять сжатие каталога WinSxS? Windows работает со сжатыми файлами в прозрачном режиме, однако при обработке таких файлов, ей может понадобиться дополнительное время на их декомпрессию/компрессию. Это может вызвать небольшое замедление при установке компонентов Windows или обновлений. Однако для современных процессоров (CPU) операция компрессии/декомпрессии файлов выполняется практически мгновенно, так что реального уменьшения скорости пользователь даже не заметит.

Wondering how to Clean Up and Compress WinSxS Folder on Windows Server/Windows 10? We can help you with it.

As part of our Server Management Services, we assist our customers with several Windows queries.

Today, let us see how our Support techs clean up the WinSxS folder on Windows Server 2016/2019.

Clean Up and Compress WinSxS Folder on Windows Server/Windows 10

The WinSxS directory will grow in size over time. Moreover, its size is not limited by anything.

Today, let us see the WinSxS folder in Windows, the reasons of its constant growth and safest ways to clean up the WinSxS folder on Windows Server 2016/2019.

  • Initially, optimize the component store and remove old versions of Windows component files left after installing Windows updates.
  •  Features on Demand – allows us to remove unused Windows components from the disk.
  • Finally, enable NTFS compression on the WinSxS folder – a way to reduce the size of the WinSxS directory using the built-in compression of the NTFS file system.

Steps to Clean Up and Compress WinSxS Folder on Windows Server/Windows 10

Firstly, get the current size of the WinSxS folder on Windows by opening the properties of the %windir%\WinSxS folder in File Explorer (or use a PowerShell script). Most file managers (including File Explorer) show a slightly larger WinSxS folder size than it takes on disk.

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

du -v c:\windows\winSXS

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

Dism.exe /Online /Cleanup-Image /AnalyzeComponentStore

Deployment Image Servicing and Management tool
[==========================100.0%==========================]
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 we can see, we can reduce the size of the WinSxS folder by (1,97 + 0,44) GB.

The DISM command also allows us to check and repair our Windows image.

DISM /Online /Cleanup-Image /RestoreHealth

How to Clean Up the Component Store (WinSxS folder) on Windows

Initially, clear the Windows Component Store (the WinSxS folder) by optimizing the storage with the command:

Dism.exe /Online /Cleanup-Image /StartComponentCleanup

The StartComponentCleanup DISM option is supported on all Windows versions starting from Windows 8 and Windows Server 2012.

After cleaning is complete, check the current size of the component store:

Dism.exe /Online /Cleanup-Image /AnalyzeComponentStore

After that, we will not be able to remove installed updates or Service Packs and the Uninstall button will disappear from the Uninstall an Update Control Panel item). To clean up old versions of components, run:

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

In Windows 7 and Windows Server 2008 R2, an additional DISM option was used to clean up old versions of components that were left over after installing service packs.

DISM /online /Cleanup-Image /spsuperseded

We can also remove old update files using the “Disk Cleanup” wizard:

1. Firstly, run the cleanmgr command as an administrator
2. Then, select the disk and in the next window, click the “Clean up system files” button.
3. Finally, select the “Windows update cleanup” option. The Disk Cleanup tool will show how much space we can free up by deleting old Windows update files. In this example, this is 324 MB. Click OK to start the cleanup.

After we finish cleaning up the component store using DISM, we can check how much disk space has been freed.

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.

As in case of any non-standard intervention into the system configuration, it is strongly recommended to create a full backup of our Windows 10 image.

1. Firstly, open the command prompt as administrator.
2. Then, stop and disable Windows Installer and Windows Module Installer services:

sc stop msiserver
sc stop TrustedInstaller
sc config msiserver start= disabled
sc config TrustedInstaller start= disabled

3. Let us 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):

icacls “%WINDIR%\WinSxS” /save “%WINDIR%\WinSxS_NTFS.acl” /t

4. Assign us as an owner of the WinSxS folder and all its subfolders:

takeown /f “%WINDIR%\WinSxS” /r

5. Grant our account full control permissions on the WinSxS directory:

icacls “%WINDIR%\WinSxS” /grant “%USERDOMAIN%\%USERNAME%”:(F) /t

6. We can now compress files in the WinSxS directory using the compact command. Because some of the files can be used by Windows, we need to specify the /i option. Otherwise, compression will stop at the first locked file (in Windows 10, we can use more advanced LZX compression):

compact /s:”%WINDIR%\WinSxS” /c /a /i *

7. Restore the owner of the WinSxS directory back to TrustedInstaller:

icacls “%WINDIR%\WinSxS” /setowner “NT SERVICE\TrustedInstaller” /t

8. Restore the original ACLs for the WinSxS folder items using the ACL backup file we created earlier:

icacls “%WINDIR%” /restore “%WINDIR%\WinSxS_NTFS.acl”

9. Restore the default startup type for the Windows Installer and Windows Module Installer services:

sc config msiserver start= demand
sc config TrustedInstaller start= demand

Now check the current size of the WinSxS folder.

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 we run it, the described compression procedure for items in the WinSxS folder will start.

[Need assistance? We can help you]

Conclusion

In short, we saw how our Support Engineers Clean Up and Compress WinSxS Folder on Windows Server/Windows 10

Are you using Docker based apps?

There are proven ways to get even more out of your Docker containers! Let us help you.

Spend your time in growing business and we will take care of Docker Infrastructure for you.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

One of my Windows Server 2012 R2 ran out of space. A quick folder analysis using the free portable tool TreeSize revealed that both Windows.old and WinSxS folders are the ones taking most of the spaces.

Folder Analysis - Windows Server 2012

On Windows desktop systems, both folders are easy to clean up with the built in tool Disk Cleanup Utility. But, it’s not the case in Windows Server, especially the more recent versions like 2012 R2. You probably could enable Desktop Experience feature to bring back the Disk Cleanup Utility but it won’t guarantee to clean up these two giant folders managed by the system upgrades and updates. If you are facing the same challenge as I do, here are the options you can take away.

WinSxS, aka Windows component store, contains all the files required for a Windows installation as well as any updates to those files within the component store. Therefore, the folder could become quite big over time. Because it’s associated with system installation it’s not a good idea just simply deleting the folder. Rather, utilizing a command-line tool called DISM, Deployment Image Servicing Management, is way more appropriate. It has a parameter /cleanup-imagethat provides a few more advanced options to reduce the size of the WinSxS folder.

First of all, you can run the following to analyze the component store to see what’s included in there.

dism /online /cleanup-image /AnalyzeComponentStore

Dism to analyze the component store

Then, run the following to remove superseded and unused system files from the system and reset the base so all existing updates cannot be removed after the command is completed.

dism /online /cleanup-image /StartComponentCleanup /ResetBase

It didn’t clean up a whole lot in my case, only claimed back a little over 1 GB space.

Note: If you are somehow still using Windows Server 2008 R2, installing KB2852386 after enabling Desktop Experience feature makes things a lot easy to clean up right with the Disk Cleanup Utility tool.

How to clean up WinSxS folder on Windows 2008 R2

How to clean up Windows.old on Windows Server 2012 R2

With Disk Cleanup out of the equation, manual cleanup seems to be the option left. Thanks to this Q&A at ServerFault, here is what I did to bring back over 50 GB of storage space.

First of all, run Sysinternals junction.exe utility to get a list of all junctions in a text file, junc.txt on my desktop.

junction.exe -s -q c:\windows.old > %UserProfile%\desktop\junc.txt

Then, run the following script in PowerShell to remove all junction points and single symbolic links on the system.

foreach ($line in [System.IO.File]::ReadLines("$env:userprofile\desktop\junc.txt"))
 {
     if ($line -match "^\\\\")
     {
         $file = $line -replace "(: JUNCTION)|(: SYMBOLIC LINK)",""
         & $env:userprofile\desktop\pstools\junction.exe -d "$file"
     }
 }

Replace with the correct path for junction.exe utility and the junc.txt files, if needed.

Once that’s done, run the following to take over ownership of the windows.old folder.

takeown /f c:\windows.old /r /d y

And reassign the full control rights to everyone.

cacls c:\windows.old /t /g everyone:F

Then, finally to remove the whole folder.

rmdir /s /q c:\windows.old

It may take a little while for the command to complete but once it’s done you will be so delighted to see how much space you just brought it back to life. Enjoy.

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Classin app download windows
  • Как изменить имя компьютера windows 10 pro
  • Как посмотреть материнскую плату на windows 10 на ноутбуке
  • Почему не работает роблокс на пк windows 10
  • Как улучшить свой рабочий стол windows 10