Sysprep штатная утилита адаптации windows к новому железу

Друзья, привет. В этой статье поговорим о штатной утилите Windows Sysprep. Её работа до сих пор на страницах сайта рассматривалась только в контексте использования инструмента, участвующего в процессе создания своих дистрибутивов операционной системы. Но эту утилиту можно использовать и в других целях. Что это за цели, и как в процессе их достижения применять Sysprep?

Sysprep – утилита, присутствующая на борту Windows 7-10 – является средством отвязки операционной системы от драйверов комплектующих конкретного компьютера и отдельных профильных данных.

Такая отвязка предусматривается преимущественно для подготовки эталонного образа Windows – состояния системы с внесёнными настройками и установленным софтом – к дальнейшему развёртыванию на множестве компьютерных устройств. Что всерьёз облегчает работу системщиков OEM-производителей и корпораций. Все те фирменные ноутбуки с предустановленными в среду Windows брендовыми надстройками и программным обеспечением, от которых попробуй ещё избавиться – это результат развёртывания на них операционной системы, эталонный образ которой создавался на базе чистого её дистрибутива и потом дорабатывался в режиме аудита. И в этом процессе на одном из этапов участвовала утилита Sysprep.

Sysprep производит удаление из Windows драйверов комплектующих компьютера, и при следующем запуске система автоматически устанавливает новые драйверы для, соответственно, новой конфигурации оборудования. Утилита также обнуляет SID, проводит очистку системного журнала событий, удаляет содержимое системной папки «Temp», удаляет точки отката – в общем, зачищает следы своей работы на текущем устройстве, чтобы с новым запуском Windows начать работу по-новому. Как если бы операционная система была только что установлена. При необходимости Sysprep может до трёх раз сбросить активацию системы.

Чтобы запустить утилиту, жмём Win+R, вписываем «Sysprep» и в открывшейся системной папке двойным кликом открываем EXE-шник.

Для каких целей можно использовать эту утилиту?

Если вы, друзья, хотите создать свою сборку Windows – со своими предустановленными программами, внедрёнными обновлениями, выполненной активацией, изменёнными настройками и т.п., вы будете использовать Sysprep перед захватом настроенного образа системы. А как создаются свои сборки Windows, этому у нас на сайте посвящён целый раздел статей.

Замена важных компьютерных комплектующих типа материнской платы или процессора в системах Windows 8.1 или 10 обычно не влечёт за собой синий экран смерти. В большей степени этому подвержена Windows 7. Но акцент на слове «обычно», ситуации могут быть разные. Лучше всё же в любой версии системы перед заменой материнки или процессора выключить Windows с предварительным запуском Sysprep. Её запуск отвяжет систему от текущих драйверов устройств (т.е. попросту удалит их). И при следующем запуске компьютера драйверы установятся по-новому. Этот способ поможет не только избежать возможного появления синего экрана смерти, но и предотвратит ещё одну проблему, которая может проявится не сразу, а через какое-то время работы компьютера в новой конфигурации – конфликт старого и нового драйвера заменённого устройства.

Запускаем Sysprep перед непосредственным выключением компьютера для замены в нём материнской платы или процессора. В окне утилиты выставляем действие «Переход в окно приветствия OOBE». В параметрах выключения выбираем «Завершение работы».

 

Если в процессе замены материнской платы или процессора Sysprep не использовалась, не беда, утилиту можно запустить в любой момент позднее. Если, конечно же, в этом есть необходимость — в работе Windows наблюдаются проблемы из-за того, что драйвер старого устройства конфликтует с драйвером нового. Запускаем Sysprep. В её окне выбираем переход в окно OOBE, а в параметрах завершения – перезагрузку.

Sysprep удалит драйвер старой материнки и процессора вместе с прочими драйверами. И, как и в предыдущем случае, при следующем запуске Windows они установятся по-новому. Это, кстати, универсальный способ решения проблем с драйверами. Его можно использовать и в других ситуациях – например, когда при сбое работы Windows или её некорректном обновлении до новой версии слетают драйверы устройств и потом не хотят устанавливаться. Sysprep может даже помочь в переустановке драйверов режима работы жёсткого диска IDE, AHCI, RAID, NVMe. Не уверен, что всегда, но в части случаев точно. Но вы можете попробовать: перед тем, как менять в BIOS режим работы жёсткого диска, сделайте сброс драйверов с помощью Sysprep.

Чтобы можно было перенести свою наработанную Windows на другой компьютер, создатели ПО для резервного копирования в своих продуктах реализуют специальные технологии по отвязке драйверов комплектующих при восстановлении из бэкапа. Такие технологии есть, например, у бэкаперов Acronis и AOMEI – соответственно, Acronis Universal Restore и AOMEI Universal Restore. Есть такая технология также у EaseUS Todo Backup. Эти технологии, по сути, делают то же, что и Sysprep, только не перед захватом образа, а на этапе развёртывания Windows, т.е. восстановления её из бэкапа. Но тогда как Sysprep можно пользоваться совершенно бесплатно, она является частью Windows, технологии типа Universal Restore обычно поставляются в платных редакциях программ для резервного копирования. И если, к примеру, Acronis весь платный, то с помощью средств резервного копирования AOMEI или EaseUS и участия утилиты Sysprep совершенно бесплатно можем перенести свою рабочую Windows на другой компьютер. Ведь у программ AOMEI Backupper и EaseUS Todo Backup базовый функционал, куда входит обычное резервное копирование и восстановление Windows, бесплатный.

Чтобы перенести наработанную Windows на другую конфигурацию железа, подготавливаем загрузочный носитель с программой для резервного копирования. Если вам, друзья, нравится программа EaseUS Todo Backup, вот статья, как создать загрузочную флешку и работать с неё, создавая системные бэкапы и восстанавливая их. А если вам нравится программа AOMEI Backupper, можете скачать готовый ISO-образ с ней для записи на флешку или оптический диск.

Загрузочный носитель с бэкапером подготовили, теперь запускаем Sysprep. В её окне выбираем переход в окно OOBE, а в параметрах выключения – завершение работы.

Запускаем компьютер с загрузочного носителя с бэкапером. Создаём резервную копию уже отвязанной от драйверов Windows.

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

При восстановлении Windows её драйверы будут установлены по-новому.


Примечание: друзья, по теме переноса Windows на другой компьютер с отличным железом смотрите также детальный мануал с использованием разных инструментов в статье сайта «Как перенести Windows 10 на другой компьютер» (применимо также к Windows 7 и 8.1).


Ещё одна функция Sysprep – возможность сброса активации. В идеале эта функция предназначается, опять же, для отвязки эталонного образа Windows от активации и поставки модифицированного дистрибутива системы без вшитого ключа продукта. Но поскольку нигде не написано и мокрой печаткой не закреплено, что эту функцию можно использовать в других целях, сброс активации с помощью Sysprep знающие люди используют для продления 30-дневного триал-срока Windows 7. Активацию системы можно сбросить трижды, следовательно, в целом триал-срок работы с «Семёркой» может составить 120 дней.

Как сбросить активацию Windows 7? Запускаем Sysprep. В её окне выбираем переход в окно OOBE, ниже ставим галочку «Подготовка к использованию», в параметрах завершения указываем перезагрузку.

Примечание: Сбросить активацию системы можно и другим способом — с помощью командной строки. Этот способ мы рассматривали в статье о Windows Embedded 7.

Сброс активации с помощью Sysprep также можно использовать для продления срока бесплатных пробных лицензий Evalution ознакомительных Windows. Такие предлагаются IT-специалистам компаний в рамках проекта TechNet Evaluation Center компании Microsoft. В число таких ознакомительных систем входит Windows 10 Корпоративная и LTSB. Их официально можно бесплатно использовать 90 дней, а потом нужно либо покупать ключ продукта, либо переустанавливать систему, чтобы заново начался отсчёт дней Evalution-лицензии. Но если под конец 90-дневного срока сбросить активацию Evalution с помощью Sysprep, Windows не нужно будет переустанавливать ещё 90 дней, а потом ещё таких же 90 дней. В итоге получим 360 дней бесплатного использования.

После использования Sysprep с указанным действием «Переход в окно приветствия OOBE» Windows запустится на этапе задания региональных и профильных параметров. Этот этап мы всегда проходим при установке системы. Здесь нужно указать страну, раскладку клавиатуры и создать новую локальную учётную запись.

В эту новую учётную запись можно даже не входить, если она сама автоматом не запустится. Если запустится, выходим на экран блокировки, заходим в свою старую учётную запись.

И потом из своей учётки можем удалить новую учётку.

  • В процессе использования утилиты sysprep у вас могут выходить различные ошибки, читайте о них в отдельной статье
  • О том, как использовать Sysprep при переносе Windows написано здесь.

  • Заметки
  • Windows

06.10.2020

Что такое Sysprep

Sysprep это стандартная программа для подготовки настроенной системы для переноса на новое железо, убирает любые идентифицирующие данные устройств и удаляет все драйвера комплектующих вместе с
системным журналом. В итоге после её применения мы получаем новую, чистую систему, но со своими старыми файлами и настройками. Программа появилась на борту системы уже в Windows NT 4.0 (1996 год).

Для чего нужен Sysprep?

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

Установка Sysprep

Данная утилита не поставляется как отдельное программное обеспечение, а идёт сразу вместе с установленной ОС Windwows и её можно найти в каталоге sysprep:

%WINDIR%\system32\sysprep

Запуск Sysprep

Программу необходимо запускать от имени Администратора и желательно из под учётной записи Администратора. Для запуска программы перейдём в каталог программы, выполнив WIN + R команду:

Sysprep

После запуска программы мы увидим следующее диалоговое окно:

Переход в окно приветствия системы (OOBE) означает что после завершения сброса при следующем запуске появится настройка первого запуска, где мы будем указывать имя пользователя, давать имя своему компьютеру и т.д,
а галочка напротив параметра Подготовка к использованию в Sysprep поможет нам сбросить активацию ОС Windows.

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

Параметры завершения работы дают нам выбор:

  • Завершение установки — выбираем в том случае, когда мы собираемся заменить материнскую плату или процессор. А сам сброс мы выподняем ДО (!) замены оборудования
  • Перезагрузка — данный пункт нам нужен в случае сброса лицензии или устранения каких-то ошибок на текущей конфигурации компьютера (без замены комплектующих) для чистой установки всех необходимых драйверов.
  • Выход — соответственно завершает сеанс пользователя по завершению.

После выбора всех параметров запускаем очистку sysprep OK

Sysprep ошибка

Произошла неустранимая ошибка при выполнении sysprep

Такая ошибка появляется в том случае, если срабатывает ограничение на количество запусков. По умолчанию в Sysprep заложено ограничение на 3 запуска. Но выход есть, обратимся к реестру
WIN + R

regedit

Идём по ветке:

HKLM/SOFTWARE/Microsoft/Windows NT/CurrentVersion/SoftwareProtectionPlatform

И меняем значения параметра SkipRearm на 1 или 0. После этого проблема должна уйти.

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

HKLM/SYSTEM/Setup/Status/SysprepStatus

И у параметра GeneralizationState выставляем значение 7. И, если есть, у параметра CleanupState выставляем значение 2

Если уже и это не помогло, то запускаем Командную строку от имени Администратора и выполняем последовательно следующие две команды:

msdtc -uninstall
msdtc -install

Тем самым мы перезапустим службу координатора распределенных транзакций MSDTC. И после этого для верности перезапустите машину. После этого ошибка должна уйти 100%

Sysprep не удалось проверить установку Windows

Иногда возникает ошибка проверки установки Windows. Для решения этой ошибки мы переходим в каталог:

C:\Windows\System32\Sysprep\Panther

И открываем на редактирование файл setupact.log. Этот файл представляет собой журнал программы sysprep. И смотрим что за ошибку мы поймали.

Отключение BitLocker

Error SYSPRP BitLocker-Sysprep: BitLocker is on for the OS volume. Turn BitLocker off to run Sysprep. (0x80310039)
Error [0x0f0082] SYSPRP ActionPlatform::LaunchModule: Failure occurred while executing 'ValidateBitLockerState' from C:\Windows\System32\BdeSysprep.dll
If you run manage-bde -status command it will show the following:

Disk volumes that can be protected with
BitLocker Drive Encryption:
Volume C: [System]

В этом случае для устранения ошибки нам нужно отключить BitLocker (это понятно из самой ошибки, если просто прочитать её). Чаше всего проблема возникает на ноутбуках с Windows 10, которые используют шифрование InstantGo. Чтобы
отключить BitLocker запускаем Командную строку от имени Администратора и выполняем следующую команду:

manage-bde -off X:

Или командой через PowerShell:

Disable-Bitlocker –MountPoint "X:"

Где X — это буква вашего системного диска.

Не удается удалить современные приложения у текущего пользователя

Error SYSPRP Package Application_2.2.5.666_x64__xxxx was installed for a user, but not provisioned for all users. This package will not function properly in the sysprep image.
Error SYSPRP Failed to remove apps for the current user: 0x80073cf2.

Такая ошибка появляется, когда вы устанавливали приложение из Windows Store или криво его удалили :-) Удалим через PowerShell командой:

Get-AppxPackage –Name Application | Remove-AppxPackage
Remove-AppxProvisionedPackage -Online -PackageName Application_2.2.5.666_x64__xxxx

Заключение

Вот собственно и всё, не знаю что ещё написать по такой небольшой, но очень полезной утилите. Надеюсь я вам помог разобраться с инструментом Sysprep, спасибо что заглянули ;)

Автору на кофе ☕ или просто поднять мотивацию писать больше статей для вас 😉 !

Отдельное спасибо всем, кто отправляет донатики 😀! Очень приятно и неожиданно. Благодаря вам сайт может и в дальнейшем обходиться без рекламных баннеров.

Все способы:

  • Утилита SYSPREP
    • Как пользоваться SYSPREP
    • Заключение
  • Вопросы и ответы: 5

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

Утилита SYSPREP

Кратко разберем, что представляет собой данная утилита. SYSPREP работает следующим образом: после запуска она удаляет все драйвера, «привязывающие» систему к «железу». Как только операция будет завершена, можно подключать системный жесткий диск к другой материнской плате. Далее мы приведем подробную инструкцию по переносу Windows на новую «материнку».

Как пользоваться SYSPREP

Перед тем как приступать к «переезду», сохраните на другом носителе все важные документы и завершите работу всех программ. Также нужно будет удалить из системы виртуальные приводы и диски, если таковые были созданы в программах-эмуляторах, например, Daemon Tools или Alcohol 120%. Еще требуется в обязательном порядке отключить антивирусную программу, если она установлена на вашем ПК.

Подробнее:
Как пользоваться Daemon Tools, Alcohol 120%
Как узнать, какой антивирус установлен на компьютере
Как отключить антивирус

  1. Запускаем утилиту от имени администратора. Найти ее можно по следующему адресу:

    C:\Windows\System32\sysprep

    Запуск утилиты SYSPEP от имени администратора в Windows 7

  2. Настраиваем параметры, как показано на скриншоте. Будьте внимательнее: ошибки здесь недопустимы.

  3. Ждем, пока утилита закончит свою работу и выключит компьютер.

  4. Отключаем жесткий диск от компьютера, подключаем его к новой «материнке» и включаем ПК.
  5. Далее мы увидим, как система запускает службы, устанавливает устройства, подготавливает ПК к первому использованию, в общем, ведет себя точно так же, как и на последнем этапе обычной установки.

    Процесс запуска системы после подготовки утилитой SYSPREP в Windows 7

  6. Выбираем язык, раскладку клавиатуры, время и денежные единицы и нажимаем «Далее».

    Выбор языка и раскладки клавиатуры после подготовки утилитой SYSPREP в Windows 7

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

    Создание нового пользователя после подготовки утилитой SYSPREP в Windows 7

    Подробнее: Как удалить учетную запись в Windows 7

  8. Создаем пароль для созданной учетной записи. Этот шаг можно пропустить, просто нажав «Далее».

    Создание пароля для нового пользователя после подготовки утилитой SYSPREP в Windows 7

  9. Принимаем лицензионное соглашение Майкрософт.

    Принятие лицензионного соглашения Майкрософт после подготовки утилитой SYSPREP в Windows 7

  10. Далее определяем, какие параметры обновлений следует использовать. Этот этап не является важным, так как все настройки можно будет выполнить позже. Рекомендуем выбрать вариант с отложенным решением.

    Настройка параметров обновления безопасности после подготовки утилитой SYSPREP в Windows 7

  11. Выставляем свой часовой пояс.

    Настройка часового пояса и времени после подготовки утилитой SYSPREP в Windows 7

  12. Выбираем текущее расположение компьютера в сети. Здесь можно выбрать «Общественную сеть» для подстраховки. Эти параметры также можно будет настроить позже.

    Настройка сетевого расположения компьютера после подготовки утилитой SYSPREP в Windows 7

  13. После окончания автоматической настройки компьютер перезагрузится. Теперь можно входить в систему и начинать работу.

    Вход в систему после подготовки утилитой SYSPREP в Windows 7

Заключение

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

Наша группа в TelegramПолезные советы и помощь

What is Sysprep and what does it do?

System Preparation Tool (Sysprep), is a Windows utility that is used to prepare a Windows installation for imaging, duplication, and deployment. Its primary purpose is to generalize a Windows installation by removing system-specific information, such as the computer’s security identifier (SID), so that the operating system can be safely duplicated and deployed to multiple machines. Sysprep is most frequently used in virtualized environments to prepare a system image which will be cloned multiple times. 

Let’s start with an example.

Step 1: Prepare the Reference Computer

Before running Sysprep, it’s important to configure the Windows installation the way you want it on the target systems. In this example, we use a Virtual Machine (VM) running Window 11 Pro, Version 23H2 as a reference machine. This reference VM has:

  • Clean windows installation,  Windows 11 Pro Evaluation, Version 23H2.
  • All drivers updated.
  • All Software updated: In this example this VM has Google Chrome and Adobe Reader installed.
  • Customize Settings: In this example, we set the UAC (User Account Control Settings) to Never notify

Below are screenshots of the reference VM

Step 2: Run Sysprep

Locate Sysprep: Sysprep is typically located in C:\Windows\System32\Sysprep. Open this directory.

Run Sysprep: Double-click on sysprep.exe to launch the Sysprep tool.

  • Choose System Cleanup Action: In the Sysprep dialog, select the “Enter System Out-of-Box Experience (OOBE)” option. This prepares the system for the first boot experience.
  • Select Generalize: Check the “Generalize” option. This removes system-specific information such as the computer security identifier (SID), making the Windows installation hardware-independent.
  • Choose Shutdown Options: Choose the “Shutdown” option if you plan to capture an image for deployment later. If you’re deploying immediately, you might select “Restart.”. We choose Shutdown option.

Optionally, you can use command line to run the Sysprep. First, open cmd as Administrator and type:

cd \Windows\System32\Sysprep

sysprep.exe /generalize /oobe /shutdown /mode:vm

You need to wait while the Sysprep is working.

After Sysprep finish generalizing, the system will shutdown. Please note that avoid turning on the reference computer until you’re prepared to capture an image.

Step 3: Capture and Deploy the Image

There are many way to perform in this step. Also, it will depend on whether the user is using a physical machine or a virtual machine:

Scenario 1: Physical Machine

Boot into Windows PE (Preinstallation Environment): You can create a bootable USB drive or other installation media to boot the machine into Windows PE.

Capture the Image: Use a tool like DISM (Deployment Image Service and Management Tool) to capture the system image. You can use a command like:

Dism /Capture-Image /ImageFile:D:\YourImagePath\YourImageName.wim /CaptureDir:C:\ /Name:”Your Image Name”

  • D:\YourImagePath\YourImageName.wim : Specify the path and name for the captured image.
  • C:\ : Replace with the drive where your Windows installation is located.

Deploy the Captured Image: You can deploy the captured image to other machines using tools like WDS (Windows Deployment Services) or third-party imaging solutions. After deploying the image, the new machines will boot into the Out-of-Box Experience (OOBE), where users will set up their Windows environment.

We will have an in depth guide about Capture and Deploy Image for this Scenario 1 in the next blog. Also, you can refer to this Microsoft Documentation to learn more about Sysprep.

For now, this blog will focus on Scenario 2.

Scenario 2: Virtual Machine

Copy the VHDX File: After running Sysprep on the original VM, now we will locate the VHDX file of the original VM and make a copy. In this case, we named it Win11-23H2-Sysprep.vhdx

Create a New VM: In my Hyper-V Manager, create a new virtual machine and specify to use an existing VHDX file for the virtual machine’s storage.

Start the New VM: Start the new VM. It will boot from the copied VHDX file and go through the Out-of-Box Experience (OOBE), allowing you to set up the new virtual machine.

Once we are on the desktop, notice that Adobe Reader and Google Chrome are installed and ready to use, just like the Reference Machine.

However, notice that the reference PC we used ealier for sysprep, the user account name “staff”. When we create a new VM and attach the VHDX, in the OOBE process , it not allow us to use “staff” again, we have to create a different user account named “staff2

This happens becuase during the Out-of-Box Experience (OOBE) process, Windows generates a unique Security Identifier (SID) for each installation. This SID is crucial for maintaining the security and integrity of the Windows operating system. If you attempt to create a new virtual machine (VM) by attaching the same virtual hard disk (VHDX) from a Sysprepped VM, Windows recognizes that the SID has already been used and prevents you from creating a user account with the same name.

To overcome this issue, we should create an Unattend.xml file during the Sysprep process. In the Unattend.xml file, you can specify the desired user account, among other configurations. In the example we just did, the absence of an Unattend.xml file can lead to the duplication of certain user-related information, including the username, which might cause issues during the OOBE process of a newly deployed virtual machine

In the next blog, we will learn how to Sysprep a system using Unattend.xml file.

Notes

First, be aware that deploying the image to a new PC may trigger reactivation prompts for some applications:

  • OEM Activation: If the reference computer uses OEM (Original Equipment Manufacturer) activation, the activation status is often tied to the hardware of that specific machine. In this case, deploying the image to other computers may not preserve the activation status, and you might need to reactivate Windows on each deployed machine.
  • Volume Licensing (VL) Activation: If the reference computer is activated using a Volume License Key (VL), the activation status can be preserved in the deployed image. This is because VL activation is designed for multiple deployments across different machines. However, it’s crucial to ensure compliance with the licensing terms associated with your Volume License Agreement.

Second, the file format of the captured image depends on the imaging tool you are using. Different imaging tools may use different file formats:

  • WIM (Windows Imaging Format):  a file-based disk image format developed by Microsoft. It is commonly used with tools like Windows Deployment Services (WDS) and the Microsoft Deployment Toolkit (MDT). WIM files can store multiple images and support features like compression.
  • ISO (Disk Image): A disk image format. While it’s often associated with creating bootable installation media, it can also be used to capture and store disk images. Tools like Rufus or ImgBurn can work with ISO images.
  • VHD (Virtual Hard Disk): a file format commonly associated with virtual machines. Some imaging tools allow you to capture and store images in VHD format. This can be useful for virtualization environments.

Conclusion

In summary, we have covered how to Sysprep Windows 11, 23H2 version in a virtual environment. Basically it involves Preparing reference machines, Run Sysprep, Capture and Deploy the Image. Moreover, one thing to note is that using an Unattend.xml file allows you to have greater control over the settings applied during the OOBE phase, including the creation of user accounts.

SysPrep (System Preparation Tool) is used to generalize the Windows 10/11 installation and prepare a customized reference Windows image for deployment to corporate computers. This allows administrators to quickly deploy a reference Windows image that includes all the all the necessary apps, drivers, settings, and security updates that your users need to get started.

What is Sysprep and how does it work?

The idea is that an administrator can prepare a reference Windows computer with all the necessary drivers, programs, and required system settings. This configured Windows image can then be captured and deployed to client computers. SysPrep is a built-in tool used to generalize the Windows image and remove computer-specific information (SID, GUID, etc).

This guide explains how to create a reference Windows computer, generalize it using SysPrep and capture the WIM image that will be installed on other computers. I will cover the following basic steps:

  • Perform a clean installation of Windows 10/11 from the original ISO image on the reference computer.
  • Use the SysPrep tool to put the Windows into the Audit Mode.
  • Configure your Windows environment: install drivers, updates, language packs, apps, configure user personalization options, configure the Desktop, create shortcuts, set files and folder permissions, etc.
  • Generalize the image using the SysPrep.
  • Boot into Windows PE and capture an image using the DISM command.
  • Copy the resulting WIM image to the installation media or use the deployment tools to install it on the users’ computers (such as MDT, WDS, DISM, or ImageX).

How to create a Windows 10 or 11 reference image

Download the latest Windows build (you can use the Media Creation tool to make Windows installation media) and perform a clean Windows installation on a reference computer or virtual machine. Do not connect the computer to the Internet at this stage (unplug the Internet connection (Ethernet) or disable your Wi-Fi adapter on your computer).

The reference builds for this article are Windows 10 22H2 or Windows 11 23H2.

Disable automatic updating of Microsoft Store apps (which can break the SysPrep process in Windows 10 and 11):

  1. Open the Local Group Policy Editor (gpedit.msc) and go to Computer Configuration > Administrative Templates > Windows Components > Store;
  2. Enable the policy Automatic Download and Install of updates;
    sysprep windows 11

Then configure the ImageState registry parameter:

reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Setup\State" /v ImageState /t REG_SZ /d IMAGE_STATE_GENERALIZE_RESEAL_TO_OOBE /f

And make changes to the file C:\Windows\Setup\State\State.ini

[State]

ImageState=IMAGE_STATE_SPECIALIZE_RESEAL_TO_OOBE

sysprep

This will prevent SysPrep from failing when processing Microsoft Store apps.

Customizing Reference Windows Image in Audit Mode with SysPrep

The next step is to customize your reference Windows image in the Audit Mode. You can boot into Audin Mode from the OOBE screen (run CTLRL+Shift+F3) or open an elevated PowerShell console and run sysprep command:

C:\windows\system32\sysprep\sysprep.exe

sysprep step by step

Select the following options:

  • System Cleanup Action: Enter System Audit mode;
  • Shutdown Options: Reboot;
  • Press the OK button.

Sysprep on Windows can be run from the command line with basic options:

sysprep.exe [/oobe | /audit] [/generalize] [/reboot | /shutdown | /quit] [/quiet] [/unattend:answer_file_name]
  • /audit — boots Windows into audit mode. In this mode, you can install additional apps and drivers;
  • /generalize — preparing Windows for image capture. All identifiers, logs, Event Viewer logs, and restore points are removed;
  • /oobe — restarts the Windows in the Welcome screen mode. The Windows Welcome screen allows users to configure Windows operating system, create new accounts, rename the computer, and perform other tasks;
  • /unattend:answer_file_name — allows you to apply the settings from the answer file to Windows during an unattended installation.

sysprep answer file

Note. In some cases, SysPrep returns the error: unable to validate your Windows installation. The cause of the error is listed in the %WINDIR%\System32\Sysprep\Panther\setupact file.

Refer to the article for other possible sysprep errors and fixes: Sysprep was not able to validate your Windows installation.

sysprep tutorial

For other SysPrep errors, you can check the log files. Depending on the stage, Sysprep may write information to one of the directories:

  • Generalize — %WINDIR%\System32\Sysprep\Panther.
  • Specialize — %WINDIR%\Panther.
  • Windows Unattended installation — %WINDIR%\Panther\UnattendGC.

The computer will automatically restart and boot into Audit Mode. Windows automatically logs on using the built-in administrator account (even if it was previously disabled). Windows will always boot into the Audit Mode until you explicitly switch your computer to Out-of-Box Experience (OOBE), Windows will always start in Audit Mode.

sysprep windows 10 step by step

The only visible sign that you’ve entered audit mode is the Sysprep dialogue box in the center of the screen. Do not close the SysPrep window, just minimize it.

You are now ready to start customising your Windows. We will take a look at some popular steps that sysops most often configure in their reference image.

Step 1 (Optional): Install OEM Information and Logo

Set your company branding info. In this example, we will set the OEMLogo, Company name, tech support website, and working hours. Create a text file oem.reg, and copy the following code into it:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\OEMInformation]

“Logo”=”C:\\WINDOWS\\oem\\OEMlogo.bmp”

“Manufacturer”=”TheITBros, LLC”

“Model”=”Windows 10 Pro 22H2”

“SupportHours”=”9am to 5pm ET M-F”

“SupportURL”=”https://theitbros.com”

Note. Create the graphic file C:\WINDOWS\oem\OEMlogo.bmp with your company logo.

To apply the REG file, double-click it, and accept the registry changes. This will import these settings into the registry.

easy sysprep windows 11

After restarting, check your branding information in the System Properties dialog:

sysprep guide

Step 2: Install the Drivers and Apps

Install all the required drivers and third-party programs you would like to see in your Windows 10/11 image.

Install all the necessary drivers for all the computers and laptop models on which you want to deploy this reference Windows image. Extract the driver files (including the *.inf files) to the local folder and use PowerShell to inject all the drivers from the source folder into the Windows image:

Get-ChildItem "C:\Drivers\" -Recurse -Filter "*.inf" |

ForEach-Object {PNPUtil.exe /add-driver $_.FullName /install}

Then you can download and install apps manually, or use the built-in WinGet package manager to install software from the WinGet repo. Let’s say, we want to install Opera, Google Chrome, VLC media player, Adobe Acrobat Reader DC, 7Zip, K-Lite Codec Pack Full, and Zoomit. Open the elevated PowerShell prompt and run the command:

winget install --id=7zip.7zip -e && winget install --id=Opera.Opera -e && winget install --id=Google.Chrome -e && winget install --id=VideoLAN.VLC -e && winget install --id=Adobe.Acrobat.Reader.32-bit -e && winget install --id=CodecGuide.K-LiteCodecPack.Full -e && winget install --id=Zoom.Zoom –e

sysprep windows 10 22h2

Note. Don’t install or update any Microsoft Store apps on a reference computer.

If you need to reboot Windows to install the application or update, you can do so. After reboot, the system will return to audit mode.

Step 3: Install Windows Security Update in Audit Mode

Windows will not allow you to install updates in audit mode by using the Windows Update section of the Settings panel since the OOBE phase is not complete.

Use the PSWindowsUpdate module from PowerShell Gallery to install the security updates from the command prompt.

  1. Install the PSWindowsUpdate module:
    Install-Module -Name PSWindowsUpdate
  2. Automatically download and install all the available Windows updates:
    PowerShell -ExecutionPolicy RemoteSigned -Command Import-Module PSWindowsUpdate;
    
    Install-WindowsUpdate -MicrosoftUpdate -AcceptAll -AutoReboot
  3. Check again for available updates:
    Get-WindowsUpdate

Step 4 (Optional): Uninstall Built-in Microsoft Store Apps

Also, you can uninstall built-in Microsoft Store (UWP apps), but it’s really up to you. So, if you don’t want to uninstall built-in apps, just skip this step.

You can remove pre-installed Microsoft Store apps in Windows 10 22H2 and Windows 11 23H2 using the following PowerShell commands:

#News app

Get-AppxPackage *BingNews* | Remove-AppxPackage

#Weather

Get-AppxPackage *BingWeather* | Remove-AppxPackage

#PowerShell

Get-AppxPackage *PowerShell* | Remove-AppxPackage

#Music app

Get-AppxPackage *ZuneMusic* | Remove-AppxPackage

#Movies and TV

Get-AppxPackage *ZuneVideo* | Remove-AppxPackage

#MS Office

Get-AppxPackage *MicrosoftOfficeHub* | Remove-AppxPackage

#People app

Get-AppxPackage *People* | Remove-AppxPackage

#Maps

Get-AppxPackage *WindowsMaps* | Remove-AppxPackage

#Help and tips

Get-AppxPackage *GetHelp* | Remove-AppxPackage

#Voice Recorder

Get-AppxPackage *WindowsSoundRecorder* | Remove-AppxPackage

#Sticky Notes

Get-AppxPackage *MicrosoftStickyNotes* | Remove-AppxPackage

#PowerAutomate

Get-AppxPackage *PowerAutomateDesktop* | Remove-AppxPackage

#Xbox and related apps

Get-AppxPackage *Xbox* | Remove-AppxPackage

#Feedback Hub

Get-AppxPackage *WindowsFeedbackHub* | Remove-AppxPackage

#Microsoft To-Do

Get-AppxPackage *Todos* | Remove-AppxPackage

#Calculator

Get-AppxPackage *WindowsCalculator* | Remove-AppxPackage

#Alarms and Clocks

Get-AppxPackage *WindowsAlarms* | Remove-AppxPackage

#Teams/Chat

Get-AppxPackage *Teams* | Remove-AppxPackage

#Your Phone

Get-AppxPackage *YourPhone* | Remove-AppxPackage

#Spotify

Get-AppxPackage *SpotifyAB.SpotifyMusic* | Remove-AppxPackage

#Screen & Sketch/Snipping tool

Get-AppxPackage *ScreenSketch* | Remove-AppxPackage

#Solitaire Collection

Get-AppxPackage *MicrosoftSolitaireCollection* | Remove-AppxPackage

#Photos

Get-AppxPackage *Windows.Photos* | Remove-AppxPackage

#OneDrive

Get-AppxPackage *OneDriveSync* | Remove-AppxPackage

#Skype

Get-AppxPackage *SkypeApp* | Remove-AppxPackage

#Xbox Console Companion

Get-AppxPackage *GamingApp* | Remove-AppxPackage

Note. An error may occur during Sysprep after you are removing some of the built-in Microsoft Store apps (check c:\Windows\Panther\setuperr.log):

Error SYSPRP Package <PackageFullName> was installed for a user, but not provisioned for all users. This package will not function properly in the sysprep image.
Error SYSPRP Failed to remove apps for the current user: 0x80073cf2.

This is a known Windows 10/11 issue and you can fix it according to the guide.

Generalizing Windows image using SysPrep

If your computer has a static IP address, change the configuration to get it automatically (from a DHCP server). Open the network adapter settings, select the IPv4 protocol properties and select Obtain an IP address automatically.

windows 10 sysprep

Or, you can use the following PowerShell script to automatically get an IP address from a DHCP server:

$IPType = "IPv4"

$adapter = Get-NetAdapter | ? {$_.Status -eq "up"}

$interface = $adapter | Get-NetIPInterface -AddressFamily $IPType

If ($interface.Dhcp -eq "Disabled") {

If (($interface | Get-NetIPConfiguration).Ipv4DefaultGateway) {

$interface | Remove-NetRoute -Confirm:$false

}

$interface | Set-NetIPInterface -DHCP Enabled

$interface | Set-DnsClientServerAddress -ResetServerAddresses

}

Now cleanup your image:

  1. Use the Disk Clean-up tool (cleanmgr.exe) to remove junk and unnecessary files from your computer’s hard disk;
    how to sysprep windows 11

  2. Empty the Recycle Bin;
  3. Remove temporary files and folders (%LocalAppData%\temp, C:\Windows\Temp, etc.);
  4. Delete all local user profiles, except for the Administrator and Default profiles.
  5. Clean up the Web Cache files in the Administrator and Default profiles:
    rd /s /q "C:\Users\Administrator\AppData\Local\Microsoft\Windows\WebCache"
    
    rd /s /q "C:\Users\Administrator\AppData\Local\Microsoft\Windows\INetCache"
    
    del /f /q /a:sh "C:\Users\Administrator\AppData\Local\Microsoft\Windows\WebCacheLock.dat"
    
    rd /s /q "C:\Users\Default\AppData\Local\Microsoft\Windows\WebCache"
    
    rd /s /q "C:\Users\Default\AppData\Local\Microsoft\Windows\INetCache"
    
    del /f /q /a:sh "C:\Users\Default\AppData\Local\Microsoft\Windows\WebCacheLock.dat"

    After everything is configured, you can expand the SysPrep windows and select the options:

  • System Cleanup Action: Enter System Out-of-Box Experience (OOBE);
  • Shutdown Options: Shutdown;
  • Check the Generalize option.

windows 11 sysprep answer file

Once the Windows image has been generalized, it will start in Out-of-Box Experience (OOBE) mode and reassign unique SIDs.

Using Answer Files with Sysprep for Unattended Windows 10/11 Installation

SysPrep allows using an answer file for unattended Windows installation. This step is optional (used to specify various image deployment options). You can skip this step, and go straight to the step of capturing a Windows image.

The answer file can contain the answer to any question you are asked during Windows Setup (region, language, product key, keyboard, account, and privacy setting, etc.). You can use the answer file to skip some of the steps during the out-of-box experience (OOBE).

How to create Windows Answer File using Windows System Image Manager

The answer file is a file with XML syntax. The preferred tool for generating the correct answer file is the Windows System Image Manager (Windows SIM).

Download the Windows Assessment and Deployment Kit (ADK) for Windows 10 or ADK for Windows 11. Use the ADK version for the Windows version you want to deploy.

Run the adksetup.exe file as an administrator. Then select Deployment Tools to install (it includes the latest version of DISM and Windows SIM).

windows sysprep

You will need the install.wim file with the Windows image you want to deploy. You can copy the install.wim file from the sources directory on the installation Windows ISO image. If only the install.esd file is available in the sources directory, you can convert ESD to WIM to get install.wim.

Let’s create an answer unattended file for Windows 10 22H2.

Run the Windows System Image Manager as an administrator (C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Deployment Tools\WSIM\imgmgr.exe). Select File > New Answer File.

sysprep win11

Specify the path to your install.wim for which you want to create an answer file for.

Wait for the SIM to mount the Windows installation image and create the catalog file (.clg). This will take some time, after which the install_Windows 10 Pro.clg file will appear in the directory with the install.wim file.

win11 sysprep

Note. If you try to open the install.wim file of your Windows 10 build using WSIM from an older version of the ADK, you may receive an error message:

Windows SIM was unable to generate a catalog.

sysprep with answer file

In order to fix this error, you need to install the latest ADK and WSIM available for your Windows build.

Select your Windows 10 edition. If there is only one edition of Windows in your install.wim file, it will be selected automatically.

Using WSIM, you can configure various parameters for the answer file. For example, you can configure the Windows product key (if you are using KMS server or MAK keys), time zone, organization and owner info, default language and region settings, input locales, etc.

First of all, we need to do the most important thing: tell Sysprep to copy all our customizations to the default user profile.

To do this, find the amd64_Microsoft-Windows-Shell-Setup__neutral in the Windows Image section. Right-click on it and select Add Setting to Pass 4 specialize.

windows 10 sysprep guide

Then, in the Answer File panel, expand section 4 Specialize > amd64_Microsoft-Windows-Shell-Setup__neutral. Set the CopyProfile value to TRUE.

sysprep w11

Additionally, you can configure the following options in the Answer file.

Pass 1 Windows PE

Choosing an installation language in WinPE:

Microsoft-Windows-International-Core-WinPE

InputLocale: en-US;

SystemLocale: en-US

UILanguage: en-US

UserLocale: en-US

Pass 7 oobeSystem

Create a local administrator account and set a password for it:

Microsoft-Windows-Shell-Setup –> UserAccounts –> LocalAccounts -> Insert New Local Account

Name: admin

Group: Administrators

how to sysprep windows 10

All empty (blank) answer file parameters must be removed.

To check the settings in answer file, select in Tools > Validate Answer File option. If you configured everything correctly, a message should appear in the Messages console: No warning or errors.

sysprep win10

Save the answer file by choosing File > Save Answer File As > autounattend.xml.

Now you can close WSIM.

Generalize Windows Image Using Answer File

Now you can use your autounattend file to Sysprep your Windows image. Run the command in the elevated command prompt (replace the path to autounattend.xml with yours):

c:\windows\System32\Sysprep\sysprep.exe /generalize /oobe /shutdown /unattend:C:\ps\autounattend.xml

windows sysprep tutorial

Hint. If you want to capture a Windows image running in a virtual machine, you can use the special Sysprep switch /mode:vm:

C:\windows\system32\sysprep\sysprep.exe /generalize /oobe /mode:vm /shutdown /unattend:C:\ps\autounattend.xml

With the /generalize option the Sysprep will remove unique computer data. This allows you to safely deploy this reference Windows image on other workstations or laptops. After executing the command, the computer will shut down.

Capture Reference Windows 10/11 Using DISM

After shutting down your computer, you can capture a customized Windows image. You can use special tools to capture a Windows image (such as MDT) or use DISM. Below we will consider the DISM option.

Boot the reference computer into Windows PE. The easiest way to access WinPE is to boot the computer from the Windows 10/11 installation media, or recovery drive.

Press Shift + F10 on the first setup screen.

Type Diskpart command. Use the list vol command to identify the drive letters. In this example, the installed Windows image is located on drive D.

Capture the image with the command:

dism /capture-image /imagefile:E:\win10referenceimg.wim /capturedir:d:\ /name:"Win10 Pro reference image"

windows 11 sysprep unattend xml

  • /Capturedir — the reference Windows folder.
  • /imagefile — the target WIM image file you want to create. Connect an additional disk or USB flash drive to the computer and save the image to it (do not specify the Windows partition drive letter here);
  • /Compress — use the /compress:maximum option for best WIM image file reduction (this will increase the image capture time, but save a disk space).

sysprep for windows 11

Hint. You can capture your reference Windows image and immediately save it to a shared network folder on your file server (or MDT host). To do this, you need to mount a network drive in WinPE before running the dism /capture-image command:

  1. Initialize network in WinPE and get IP address from DHCP server:
    wpenit
  2. Map a shared network folder using the net use command:
    Net use E: \\192.168.31.20\share

    sysprep windows

  3. Provide user credentials to access shared folder;
  4. Now you can capture an image to a shared folder over the network.

Note. Note that the reference WIM image you get may be significantly larger than the clean Windows 10 or 11 installation image.

Copy the reference WIM image you’ve got to the installation drive media (copy and replace file ..\sources\install.wim), or put it into your deployment software (MDT, SCCM).

Now you can deploy your customized Windows image to computers across the company using MDT, WDS, SCCM, etc.

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Vivo usb driver для windows
  • Qttabbar windows 10 не устанавливается
  • Как сделать smb сервер на windows 11
  • Открыть доступ к микрофону windows 10
  • Установка разрешения экрана через реестр windows 7