Skip to main content

πŸ§ͺ Offline Boot Testing & Generalization of VHDX OS Images

VHDX Imaging and Azure Upload Process Guide

This guide follows the Disk2vhd imaging and Azure upload process. In networks where the .vhdx is synced to local hypervisor storage, the image must be tested offline to validate bootability before being generalized and cleaned.


1. πŸ”Œ Boot Test in Local Staging Hypervisor

Objective:

Ensure the .vhdx image boots in a virtual machine within a completely offline staging environment.

Steps:

  1. Import the .vhdx into your hypervisor (e.g., Hyper-V, Proxmox, VMware Workstation).
  2. Create a test VM:
    • Connect the disk as the primary boot volume.
    • Ensure no internet/network adapters are connected.
  3. Power on the VM.

🏒 Special Case: Ridgebrook Client Deployment

For Ridgebrook:

  • Images stored in the Azure file share:
    • Storage account: clientosimages01e2usdtc
    • File share: client-os-images-01
  • The image should be synced to the local staging hypervisor:
    • Hypervisor name: ELDERBRAIN
    • Local path:
      D:\Virtual Hard Disks\client-os-images-01
  • Ridgebrook .vhdx images should be placed into a subfolder matching their PSA company name (e.g., ridgebrook-industrial).

Once synced, follow the standard boot validation and conversion process below.


2. πŸ”„ Convert MBR to GPT (If Needed)

If the VM fails to boot, the .vhdx likely uses MBR instead of GPT.

βœ… Option 1: MBR2GPT (Recommended)

Steps:

mbr2gpt /validate /disk:0 /allowFullOS
mbr2gpt /convert /disk:0 /allowFullOS

Make sure the OS volume is the last volume and delete any non-essential partitions (see below).

⚠️ Option 2: gptgen (Advanced / Manual Bootloader Required)

gptgen is a third-party tool that can convert MBR to GPT when MBR2GPT fails or is unsupported (e.g., on older systems or modified layouts). However, it does not set up the bootloader automatically.

Key Points:

  • You must manually recreate the EFI partition.
  • You must manually install the UEFI bootloader using bcdboot after conversion.
  • Proceed only if MBR2GPT is not usable.
  • Always follow up gptgen with Step 4: Rebuild BCD Bootloader.

3. πŸ“Ό Cleaning Up Partitions With DiskPart

Target Partition Layout (Post‑Conversion):

Partition Purpose Size
1 EFI System 4 GB
2 Recovery 4 GB
3 OS Volume Remainder

Why fixed sizes? Microsoft has misaligned these in the past β€” we standardize to 10 GB for EFI and Recovery to avoid risk.

DiskPart Steps:

diskpart
list disk
select disk 0
list partition

Delete unwanted partitions (OEM, redundant recovery, etc).

Create EFI:

create partition efi size=4096
format quick fs=fat32 label="System"
assign letter=S

Create Recovery (optional):

create partition primary size=4096
format quick fs=ntfs label="Recovery"
assign letter=R

4. πŸ₯Ύ Rebuild BCD Bootloader

bcdboot C:\Windows /s S: /f UEFI
  • C: = OS path
  • S: = EFI partition
  • /f UEFI = Force GPT boot

5. πŸ§‘β€πŸ’» REQUIRED: Backup & Remove User Profiles

Before proceeding, you must remove all local user accounts and profiles to avoid SID duplication and profile conflicts. This is required for all images.

Step 1: Backup Profiles with ProfWiz (if needed)

Use ForensiT User Profile Wizard (ProfWiz) to back up profiles if you need to preserve any data.

Step 2: Delete Local User Accounts and Profiles (PowerShell)

# Get the current user
$currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name.Split('\')[-1]

# Remove local user accounts except system accounts and the current user
$users = Get-LocalUser | Where-Object {
    $_.Name -notin @('Administrator','DefaultAccount','Guest','WDAGUtilityAccount',$currentUser)
}
foreach ($user in $users) {
    Remove-LocalUser -Name $user.Name
}

# Remove user profiles except system accounts and the current user
$profilessystemProfiles = @('Administrator','DefaultAccount','Guest','WDAGUtilityAccount','Public',$currentUser)
$profileFolders = Get-ChildItem -Path 'C:\Users' -Directory | Where-Object {
    $_.Name -notin $systemProfiles
}

foreach ($folder in $profileFolders) {
    try {
        # Remove profile registry entry
        $profileSid = (Get-CimInstance Win32_UserProfile | Where-Object { $_.LocalPath -likeeq 'C:\\Users\\*'$folder.FullName -and}).SID
        if ($_.LocalPath -notmatch 'Administrator|DefaultAccount|Guest|WDAGUtilityAccount') -and
    ($_.LocalPath -notmatch [regex]::Escape($currentUser))
}
foreach ($profile in $profiles)profileSid) {
            Remove-CimInstance -InputObject (Get-CimInstance Win32_UserProfile | Where-Object { $_.SID -eq $profileSid }) -ErrorAction SilentlyContinue
        }
        
        # Force remove profile folder
        Remove-Item -Path $folder.FullName -Recurse -Force -ErrorAction Stop
        Write-Host "Removed profile: $($folder.FullName)" -ForegroundColor Green
    } catch {
        Write-Host "Failed to remove profile: $($folder.FullName) - $_" -ForegroundColor Red
    }
}

⚠️ Permanently deletes all local user accounts and profiles except system accounts and the currently signed-in user.


6. πŸ’Ύ REQUIRED: Skip OOBE with unattend.xml

You must use an unattend.xml to skip setup UI and telemetry for all images.

Sample unattend.xml Snippet

<?xml version="1.0" encoding="utf-8"?>
<unattend xmlns="urn:schemas-microsoft-com:unattend"
          xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <settings pass="oobeSystem">
    <component name="Microsoft-Windows-Shell-Setup"
               processorArchitecture="amd64"
               publicKeyToken="31bf3856ad364e35"
               language="neutral"
               versionScope="nonSxS">
      <AutoLogon>
        <Username>installadmin</Username>
        <Password>
          <Value>DTC@dental2025</Value>
          <PlainText>true</PlainText>
        </Password>
        <Enabled>true</Enabled>
        <LogonCount>1</LogonCount>
      </AutoLogon>
      <OOBE>
        <HideEULAPage>true</HideEULAPage>
        <HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE>
        <NetworkLocation>Work</NetworkLocation>
        <ProtectYourPC>3</ProtectYourPC>
        <SkipMachineOOBE>true</SkipMachineOOBE>
        <SkipUserOOBE>true</SkipUserOOBE>
      </OOBE>
      <TimeZone>Eastern Standard Time</TimeZone>
      <UserAccounts>
        <LocalAccounts>
          <LocalAccount wcm:action="add">
            <Name>installadmin</Name>
            <Group>Administrators</Group>
            <Password>
              <Value>DTC@dental2025</Value>
              <PlainText>true</PlainText>
            </Password>
          </LocalAccount>
        </LocalAccounts>
      </UserAccounts>
    </component>
  </settings>
  <settings pass="specialize">
    <component name="Microsoft-Windows-ApplicationExperience"
               processorArchitecture="amd64"
               publicKeyToken="31bf3856ad364e35"
               language="neutral"
               versionScope="nonSxS">
      <AITEnable>false</AITEnable>
    </component>
    <component name="Microsoft-Windows-ErrorReportingCore"
               processorArchitecture="amd64"
               publicKeyToken="31bf3856ad364e35"
               language="neutral"
               versionScope="nonSxS">
      <DisableWerReporting>true</DisableWerReporting>
    </component>
  </settings>
</unattend>

7. πŸ“ Optional (But Highly Recommended) Pre-Generalization Cleanup

Before generalization, consider performing the following steps to ensure a clean, reusable image. These are optional but highly recommended for images that will be widely distributed.

πŸ” Clear Agent Identity & Token Data (Preserve Services, PowerShell)

Tool Remove From Registry Clear File System Path
NinjaRMM HKLM\SOFTWARE\WOW6432NODE\NinjaRMM C:\ProgramData\NinjaRMMAgent
Veeam Agent HKLM\SOFTWARE\Veeam\Veeam Endpoint Backup C:\ProgramData\Veeam
# Remove NinjaRMM registry key
Remove-Item -Path 'HKLM:\SOFTWARE\WOW6432NODE\NinjaRMM\Agent\NodeId' -Force -ErrorAction SilentlyContinue

# Remove Veeam registry key
Remove-Item -Path 'HKLM:\SOFTWARE\Veeam' -Recurse -Force -ErrorAction SilentlyContinue

# Remove NinjaRMM and Veeam folders
Remove-Item -Path 'C:\ProgramData\NinjaRMMAgent' -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item -Path 'C:\ProgramData\Veeam' -Recurse -Force -ErrorAction SilentlyContinue

❗ Do not delete agent service keys under HKLM\SYSTEM\CurrentControlSet\Services.

πŸ₯΅ Windows Log Cleanup (PowerShell)

# Remove Windows event logs
Remove-Item -Path 'C:\Windows\System32\winevt\Logs\*' -Force -ErrorAction SilentlyContinue

# Remove Panther logs
Remove-Item -Path "$env:SystemRoot\Panther\*" -Force -ErrorAction SilentlyContinue

8. πŸ“Έ Create VM Checkpoint Before Generalization

⚠️ CRITICAL STEP: After all cleanup and preparation, create a checkpoint/snapshot of your VM. This allows you to restore and retry if generalization fails.

Steps:

  1. In your hypervisor management console, create a checkpoint/snapshot
  2. Name it appropriately (e.g., "Pre-Sysprep-Checkpoint")
  3. This allows you to restore and retry if sysprep fails

9. 🎯 Generalization (Sysprep) and Appx Package Removal (Final Steps)

Step 1: Run Generalization (Sysprep)

sysprep /generalize /oobe /shutdown /unattend:C:\Windows\System32\Sysprep\unattend.xml

Expected Outcome: Sysprep may fail on the first attempt due to problematic packages. This is normal and expected.

Step 2: If Sysprep Fails, Remove Problematic Windows Packages

After a failed sysprep attempt, analyze the logs and remove problematic packages.

Review setuperr.log

Open:

C:\Windows\System32\Sysprep\Panther\setuperr.log

Look for entries such as:

Package <Name> cannot be removed and is preventing Sysprep

Remove Identified Packages via PowerShell

βœ… Include asterisks (*) before and after the package name for fuzzy matching.

Get-AppxPackage -AllUsers *PackageName* | Remove-AppxPackage -AllUsers

If Get-AppxPackage does not list the package, use DISM:

dism /Online /Remove-ProvisionedAppxPackage /PackageName:*PackageName*

You can script removal for multiple packages by parsing the log.

πŸ›‘ Run from an elevated PowerShell session and verify success before continuing.

Retry Generalization

After removing problematic packages, run sysprep again:

sysprep /generalize /oobe /shutdown /unattend:C:\Windows\System32\Sysprep\unattend.xml

Repeat this process until sysprep completes successfully without errors.

βœ… Final Checklist

  • Booted offline on hypervisor
  • Converted to GPT with valid partitions
  • Optional: user profiles backed up and deleted
  • Agent identities reset (binaries remain)
  • Problematic packages removed based on setuperr.log
  • unattend.xml disables OOBE + telemetry
  • Sysprep executed successfully