How to run WinRE Manager on a single machine or across a managed fleet.
There are two ways to deploy WinRE Manager. Pick the one that matches your situation.
For a single broken machine, run the production script once from an elevated PowerShell prompt. It inspects the machine, repairs the recovery environment, writes a state file, and exits. There is no installer, no service, and no configuration file to maintain.
As of v48 patch 2, the script refuses to run unelevated in milliseconds. The refusal is a single FATAL log line (FATAL: WinRE Manager requires an elevated (Administrator) PowerShell session.) and exit code 3, before the program lock, before hardware probes, and before any network fetch. The guard creates the log directory itself so its FATAL message has somewhere to be written. Before v48 patch 2, an unelevated launch proceeded through hardware detection, manifest fetch, VMD detection, and the multi-minute GitHub base-WIM download before failing at Mount-WindowsImage with The requested operation requires elevation. — a failure mode that wasted roughly four minutes per run in the 2026-10-05 field log. Both the interactive Administrator session and the SYSTEM context used by the scheduled task pass the guard.
# Elevated PowerShell (Run as Administrator)
powershell -ExecutionPolicy Bypass -File .\scripts\WinRE.ps1 -DryRun # walk the flow, log every decision, change nothing
powershell -ExecutionPolicy Bypass -File .\scripts\WinRE.ps1 # actually deploy
The -ExecutionPolicy Bypass -File form applies the bypass only to the child process; it does not change the machine’s execution policy.
If you want to inspect the machine first, run the read-only harness (Test-WinRE.ps1). It requires no elevation and modifies nothing. See the README for the harness menu options.
As of v49, the recommended single-machine path is the wrapper. scripts\WinRE-Manager.cmd opens a menu grouped into SAFETY, DIAGNOSTICS, MAINTENANCE, REPAIR, and RECOVERY sections. Backup is the first option an operator sees and Restore is the last of the numbered options; the destructive repair run sits after the preparatory options and before Restore and Quit, so the safe and preparatory options are read first. The wrapper is the recommended entry point for a first-time user; direct script invocation is for scripting, CI, and pinned-version deployments. As of v50 patch 1, the [8] Restore and [C] Cleanup entries are shown unconditionally — the v49 patch 2 behaviour that hid them when no default-location backup existed was reversed; the screens themselves now explain when no backup exists, and the restore screen requires an explicit path rather than defaulting to a nonexistent one. See the README’s menu table for the full option list.
For a single-machine deployment, the rest of this document is reference material — the exit-code table, the Audit Mode precondition, and the Device Encryption policy all apply to a one-off run exactly as they apply to a fleet run. You can skip the scheduled-task sections.
For a managed fleet, deploy the script as a scheduled task running as NT AUTHORITY\SYSTEM, triggered at boot and weekly. This is the recommended model. Every machine keeps its recovery environment healthy on its own; a healthy machine’s fast path is dominated by Windows’ own CIM and PnP enumeration (typically 10–20 seconds), and a full repair runs only when something has changed.
The sections below this point cover the fleet deployment in detail: how to create the task, where to put the script, how to handle the Audit Mode precondition, how to interpret the exit codes, and how to roll out in rings.
Run WinRE.ps1 as NT AUTHORITY\SYSTEM from a scheduled task, triggered at boot and weekly. The script is fully idempotent; running it on a healthy machine costs a few seconds of CIM and PnP enumeration and a read-only scan.
Do not run it from a user logon script. It modifies partition tables and the BitLocker state of the target recovery partition; those operations require SYSTEM.
A healthy machine’s boot-trigger run is a no-op: the fast path runs, exits 0, and touches nothing. It does write a few lines to the log at every boot. If the boot-time delay or the per-boot log entries are unacceptable, change the scheduled task’s trigger from BootTrigger to a calendar-only trigger. The project’s recommendation is boot + weekly because a boot-time run catches machines that were offline during the weekly window.
The script’s design is organized around four rules, in this order — see docs/architecture.md for the full hierarchy.
reagentc /disable → reagentc /enable window.Rules 1–3 are invariants: no deployment scenario should weaken them. Rule 4 is the working rule: the discipline that makes the fast path and the enable-only path free of side effects, and that makes the destructive path fail safe.
Each rule has a direct operational translation for a fleet operator.
The script’s destructive sequence is protected by a read-only plan, a fail-closed layout assertion, and a reversible shrink window. It does not need to be bullet-proof to be deployed; it needs to be canaried so that any regression is caught on one machine, not a thousand.
Before pushing to a fleet, run on one machine end-to-end:
powershell -ExecutionPolicy Bypass -File .\scripts\Test-WinRE.ps1 # read-only, no elevation
powershell -ExecutionPolicy Bypass -File .\scripts\WinRE.ps1 -DryRun # walk the flow, log every decision, change nothing
powershell -ExecutionPolicy Bypass -File .\scripts\WinRE.ps1 # actually deploy
Confirm exit 0 and Operating mode: DEDICATED in the log. Only then expand the ring.
The v49 release adds three pre-deployment gates that narrow what the pipeline will deploy — a source-ownership classification (a foreign WIM that a vendor populated with its own drivers is preserved as-is rather than stripped and re-injected), a never-downgrade storage-driver check (a candidate image that would inject a storage driver older than one already present in the mounted image is discarded entirely — the source is preserved and the run defers), and a pre-deployment storage-applicability gate (which runs inside Step 3, after injection is confirmed complete, before ResetBase and before the dismount, and is the last refusal before the WIM is written to the active route). Each of these changes the pipeline’s deployment decision on at least some machines; the ScriptVersion bump from 48 to 49 is what converges the fleet onto the new pipeline. See the “v49 migration” section below for the fleet-level rollout behaviour.
The one case in which the script cannot guarantee a working recovery route on a single run is the post-deletion residual corner: a failure after the old recovery partition has been deleted, on a machine whose C: is encrypted, with no successful retry. The trigger set is wider than the commonly cited New-Partition or Format-Volume pair: the whole-layout assertion (Assert-RecoveryPartitionLayout), drive-letter availability, drive-letter assignment, in-place decryption of the new partition, the post-delete extension fallback, the post-delete geometry verification, the planned-extent-available re-check, and the recovery-partition deletion itself when the previous route cannot be restored, all reach the same corner. The correct operational response is not to interrupt the script while it is inside the destructive window — every interruption between the delete and the enable is an opportunity for the machine to land in that corner.
Concretely:
WinRE.ps1 process if it appears to be slow. A full-update pass on an NVMe machine takes 3–5 minutes of I/O; the destructive window is a small fraction of that. If you kill the process inside the window, the recovery route is not restored by the script and the next run must recover from whatever state the interruption left.The scheduled task’s own ExecutionTimeLimit (PT6H for the XML template above; 24 hours for the wrapper’s install option) and the script’s internal timeouts (300-second BitLocker polling, 5-second sleeps, 15-second network timeout) are the effective limits inside that. Nothing outside the script needs to enforce a shorter one.
If a Repair or Restore run is interrupted, the v49 temporary resume task registers itself on every Repair or Restore run and fires at boot+1m and one-shot at T+1h. The task is deleted on clean completion and preserved on interruption — including Ctrl+C, a hard kill, a reboot mid-run, an unhandled exception in the outer catch, and the three restore mid-transformation failure paths (two from v49; one from v50 patch 3). The resume run re-invokes the script with its default Repair action, which completes the operation from the checkpoint. Do not delete the resume task manually unless you intend to abandon the interrupted operation — see the “Temporary resume task” section below.
v48 expands the destructive-surface scope. As of v48 patch 1, the intervening-anchor path extends the destructive window’s entry to include a resize of the intervening data partition (typically D:) instead of the OS partition. The window’s scope is unchanged — the same partition-delete / create / format / deploy / register sequence runs — but the pre-shrink target may be the anchor rather than C:. The operational guidance above applies to the intervening-anchor case without change. The narrow scope means the participating partitions are predictable: one non-recovery data partition immediately preceding the type-coded recovery cluster, on the OS disk, validated before any mutation.
reagentc /disable → reagentc /enable window: do not schedule around itThe window is the interval during which WinRE is not registered and the recovery partition is in the process of being replaced. On a modern SSD the window is typically 15–45 seconds for the delete / create / format / deploy / reagentc /setreimage / reagentc /enable sequence. On a spinning disk or a very large WIM it can be longer.
Rule 3 is enforced by the script’s own ordering — every preparatory step that does not require a disabled WinRE runs before the disable. Your scheduling decisions should not undo that.
ExecutionTimeLimit is the correct upper bound; a second, shorter policy that runs in parallel can kill the run at the worst possible moment.The single-run recovery story is: Restore-PreviousWinRERoute on delete failure, Remove-OrphanPartition plus Restore-OSPartitionSize on create failure, and the enable-only path on a clean-but-disabled state. These handle every ordinary failure. They do not handle a process kill inside the window — but as of v49 the resume task catches the interruption case and re-invokes the script on the next boot or within the hour.
Rule 4 has four concrete operational consequences.
ScriptVersion forces one full-update pass per machine. Do it only when there is a reason — the migration sections below describe the seven version boundaries that do this deliberately.EXIT_FATAL with a “manual intervention required” message. Retrying automatically produces the same result. Resolve the underlying enable failure, delete the state file, then re-run.Before the first run on any machine, confirm:
EXIT_WARNING before any state mutation. The refusal is a stable, named deferral: a machine in the fleet whose architecture is not x64 will continue to exit 2 on every run until the manager adds support or the machine is replaced.File Backed Virtual and at least one other disk is on a physical bus — the native-boot VHD/VHDX topology, where the running OS disk is a VHD/VHDX stored on a host physical disk. A hypervisor guest whose entire storage stack is virtual (every other disk on Virtual or File Backed Virtual) is not refused and runs the full pipeline normally. The gate exits EXIT_WARNING before any partition or WinRE change. Resize-Partition and New-Partition against a VHDX-backed volume have different semantics than against a physical disk; the pipeline has not been validated under that topology. This is a stable deferral, and the gate has no -DryRun carve-out — a dry run on a VHDX-boot host also exits EXIT_WARNING.C:\Program Files\7-Zip\7z.exe, or winget available so the script can install it.gist.github.com, api.github.com, raw.githubusercontent.com, downloads.dell.com, ftp.ext.hp.com, and the vendor-specific Lenovo endpoints (download.lenovo.com, support.lenovo.com — the latter is only reached by the map builder, not by production).EXIT_WARNING when no eligible volume has 3 GiB free. See the “Workspace selection” section below.There is no BitLocker precondition on the OS volume. The v43 patch 5 (further revision 5) policy is target-volume-based: the enable-only and dedicated-partition paths do not depend on C:’s BitLocker state at all. If the target recovery partition is encrypted, the script decrypts it in place via Set-RecoveryPartitionReadyForWinRE before calling reagentc. The only route that depends on C:’s BitLocker state is the OS-fallback route, because on that route the target volume is C:. The destructive partition path does not depend on C:’s state either — as of v44 patch 6 it does not consult C: at all. Neither the OS-fallback gate nor the destructive path modifies C:’s BitLocker state. See the “Device Encryption” section below.
The harness’s System diagnostic (scripts\Test-WinRE.ps1 Option 1) reports ImageState, C:’s BitLocker state, and the target recovery partition’s BitLocker state. As of harness v28 it also reports the machine’s present SCSIAdapter-class storage controllers, which is the input the v49 pre-deployment storage-applicability gate reads. Run it on a representative machine before pushing the task to a fleet.
Create the task with schtasks.exe, or as an XML payload via Group Policy / Intune.
schtasks.exeschtasks /Create /TN "WinRE Manager" ^
/TR "powershell.exe -NoProfile -ExecutionPolicy Bypass -File C:\ProgramData\OEM\WinRE.ps1" ^
/SC ONSTART /RU SYSTEM /RL HIGHEST /F
schtasks /Create /TN "WinRE Manager Weekly" ^
/TR "powershell.exe -NoProfile -ExecutionPolicy Bypass -File C:\ProgramData\OEM\WinRE.ps1" ^
/SC WEEKLY /D SUN /ST 03:00 /RU SYSTEM /RL HIGHEST /F
Save as WinRE-Manager.xml and register with schtasks /Create /XML WinRE-Manager.xml /TN "WinRE Manager":
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<RegistrationInfo>
<Description>Self-healing Windows Recovery Environment manager.</Description>
<URI>\WinRE Manager</URI>
</RegistrationInfo>
<Triggers>
<BootTrigger>
<Enabled>true</Enabled>
<Delay>PT2M</Delay>
</BootTrigger>
<CalendarTrigger>
<StartBoundary>2026-01-04T03:00:00</StartBoundary>
<Enabled>true</Enabled>
<ScheduleByWeek>
<DaysOfWeek><Sunday /></DaysOfWeek>
<WeeksInterval>1</WeeksInterval>
</ScheduleByWeek>
</CalendarTrigger>
</Triggers>
<Principals>
<Principal id="Author">
<UserId>S-1-5-18</UserId>
<RunLevel>HighestAvailable</RunLevel>
</Principal>
</Principals>
<Settings>
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
<AllowHardTerminate>false</AllowHardTerminate>
<StartWhenAvailable>true</StartWhenAvailable>
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
<IdleSettings>
<StopOnIdleEnd>false</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
<AllowStartOnDemand>true</AllowStartOnDemand>
<Enabled>true</Enabled>
<Hidden>false</Hidden>
<RunOnlyIfIdle>false</RunOnlyIfIdle>
<WakeToRun>false</WakeToRun>
<ExecutionTimeLimit>PT6H</ExecutionTimeLimit>
<Priority>4</Priority>
</Settings>
<Actions Context="Author">
<Exec>
<Command>powershell.exe</Command>
<Arguments>-NoProfile -ExecutionPolicy Bypass -File C:\ProgramData\OEM\WinRE.ps1</Arguments>
</Exec>
</Actions>
</Task>
Notes on the settings:
MultipleInstancesPolicy = IgnoreNew prevents two scheduled runs from overlapping. A long defrag /x on a nearly-full volume can take 30+ minutes. It has no effect on processes launched outside the scheduled task — see “One instance per machine” below for how the script defends itself against manual invocations.ExecutionTimeLimit = PT6H gives the run enough headroom. No single internal operation can hang indefinitely — the longest is a 300-second BitLocker polling timeout — and the aggregate runtime of a full-update pass is well under an hour on any hardware this project supports. Do not add a shorter limit at the orchestrator level — see Rule 3 above.RunOnlyIfNetworkAvailable = false is deliberate as of v44 patch 5. The script now has an offline fallback: when the manifest fetch fails, it trusts the state file’s stored DesiredStateId and takes the fast path if the local safety checks pass. With true, the task would not fire when the network is down, so the fallback would only help manual invocations — not the scheduled path where the machine actually needs it. The offline fallback is self-limiting (EXIT_WARNING when a full update is needed, never a silent partial deployment) and safe on a machine whose state file is valid. A first deployment on a machine with no state file will still exit EXIT_FATAL when offline, which is correct: the live manifest is required to compute the initial DesiredStateId. See the “Offline behavior” section below.StartWhenAvailable = true handles missed triggers after a cold boot.The scripts\WinRE-Manager.cmd wrapper’s install option (menu option 5 — Install automatic maintenance) does not use the paths in the XML above. It installs a copy of WinRE.ps1 at:
C:\ProgramData\OEM\WinRE-Manager\WinRE.ps1
and registers the task against that copy. Patch 5 checks the destination’s ancestry and existing file for reparse points and untrusted permissions before installation. The volume root additionally permits TrustedInstaller ownership while still checking its effective write/delete permissions. Missing directories are created with protected SYSTEM/Administrators permissions; existing untrusted directories or files are refused without changing their ownership or ACLs. The source is staged in a protected, newly created file and SHA256-verified before publication. A final read handle prevents writes or deletion during verification and task registration. Preparation or staging failure leaves a previous installed script and task intact. A publication failure can leave the installed path missing or changed; the verified staging file is retained where it remains available, and its path is reported for recovery. Check the installed path before relying on an existing task after that failure. The task survives deletion or relocation of the operator’s original files.
The wrapper’s task uses a profile equivalent to the XML above for the security-relevant settings — SYSTEM account, highest run level, IgnoreNew, StartWhenAvailable, battery-allowed, no idle requirement, and — deliberately — network not required, so the offline fallback fires on scheduled runs. The schedule and time-limit settings differ intentionally: the wrapper uses boot+5m and every-30-days-at-03:00 triggers rather than the XML template’s boot+2m and weekly triggers, and a 24-hour execution time limit rather than the XML template’s 6 hours. Both trigger schedules and both time limits are well above the effective runtime of any run the script produces, and the differences are not load-bearing.
The wrapper’s removal option (menu option 6 — Remove automatic maintenance) unregisters the task and leaves the installed copy in place. A subsequent reinstall checks and refreshes that copy. The removal screen tells the operator how to delete the containing directory manually.
v50 note. The same directory (C:\ProgramData\OEM\WinRE-Manager\) holds the v50 patch 1 manager config file manager.json, written by the production script’s Add-ManagerBackupRoot after a successful backup. The two files are distinct artifacts: WinRE.ps1 is the installed script the maintenance task invokes; manager.json is the durable settings file the cleanup helper reads. Removing the wrapper’s containing directory deletes both; if you want the script gone but the backup-root catalogue preserved, remove only WinRE.ps1.
The XML template above is for a fleet operator who wants to hand-author the task. If you use the wrapper’s install option instead, the task name, script path, and trigger schedule differ from the XML template’s. Both approaches produce equivalent execution on the machine; the choice is which one the operator wants to maintain.
WinRE.ps1 assumes exclusive access to its selected image workspace and to the recovery partition it is operating on. Full updates select an eligible fixed NTFS volume and store the selection in the checkpoint for resume. As of v44 patch 4, the script enforces single-instance execution with a startup file lock.
Before any state-modifying action, and immediately after the startup banner, WinRE.ps1 opens C:\ProgramData\OEM\Logs\WinREManager.lock with an exclusive handle:
$Script:ProgramLockStream = [System.IO.File]::Open(
$lockPath,
[System.IO.FileMode]::OpenOrCreate,
[System.IO.FileAccess]::ReadWrite,
[System.IO.FileShare]::None
)
FileShare.None is enforced by the Windows kernel. Cross-session and cross-privilege exclusion are guaranteed by the OS, not by a security descriptor the script would have to configure. The handle is released automatically when the process exits, cleanly or after a crash — there is no stale-lock recovery logic to get wrong.
The lock is not acquired under -DryRun. A dry run is read-only and safe to run concurrently with a live deployment, so an operator can inspect a machine with WinRE.ps1 -DryRun or scripts\Test-WinRE.ps1 while a scheduled run is in progress.
The lock is released last in the finally block, after the WIM-mount discard and after every temporary drive letter has been cleaned up. This ensures the lock is held until all cleanup is complete, so a waiting second instance cannot begin work while the first is still releasing resources.
A second WinRE.ps1 process launched while another instance holds the lock fails fast. The log records:
[WARN] Another WinRE Manager instance is already running (program lock file is exclusively held). Exiting without making any changes. This is not a deployment failure - the other instance is doing the work and will complete on its own. …
The second instance exits with EXIT_WARNING (code 2) within seconds, before the Audit Mode guard, before the hardware check, and before any state-modifying action. It has consumed no state, written no state file, and left no checkpoint.
This is a change from the pre-patch-4 behavior. Before the lock, a concurrent instance would reach Step 2 and fail with FATAL ERROR: Cannot rename because item at '<workspace>\winre.wim' does not exist., which the orchestration layer saw as EXIT_FATAL (code 3). As of patch 4, the same scenario produces a clean EXIT_WARNING from the second instance.
C:\ProgramData\OEM\Logs\WinREManager.lock remains on disk between runs. It is not deleted on release, and it is empty by design — nothing is ever written to it. Its existence does not indicate a running instance. Only an active exclusive handle on the file blocks a second instance. Operators inspecting the log directory should not mistake the file’s presence for a stuck process.
What it protects against. The MultipleInstancesPolicy = IgnoreNew setting on the scheduled task prevents two scheduled runs from overlapping. Windows will refuse to start a second instance of the task while the first is still running.
What it does not protect against. A manual invocation — from an interactive PowerShell session, an RMM tool’s “run now” button, an Intune remediation script, or anything else that launches WinRE.ps1 outside the scheduled task — can overlap with a scheduled run. IgnoreNew is a property of the task, not of the script, so it has no effect on processes launched any other way. The v44 patch 4 file lock closes this gap for every launch path: the manual invocation and the scheduled run cannot both hold the lock.
The v49 temporary WinRE Manager - Resume task does not participate in the program lock directly — it invokes the production script with its default Repair action, which acquires the lock normally. A resume run that coincides with a scheduled run is serialized by the same lock, and whichever side loses the race exits with the same Another WinRE Manager instance is already running message.
WinRE.ps1 manually on a machine that has the scheduled task installedThe lock makes manual invocations safe, but a manual run that coincides with a scheduled run will still find itself on one side or the other of the lock:
EXIT_WARNING and the “Another WinRE Manager instance is already running” message. This is not a failure. Wait for the scheduled run to complete and try again.EXIT_WARNING on its own side.schtasks /Change /TN "WinRE Manager" /DISABLE (and the same for the Weekly task) before, /ENABLE afterwards.scripts\Test-WinRE.ps1 does not acquire the lock, does not touch the workspace, does not modify partitions, and is safe to run at any time, alongside any number of other processes.If the lock cannot be acquired for a reason other than contention — a permission error on C:\ProgramData\OEM\Logs\, a missing Logs directory that could not be created, or a transient filesystem issue — the script logs:
[WARN] Could not set up program lock at C:\ProgramData\OEM\Logs\WinREManager.lock : <error> - Backup may continue, but Repair and Restore require exclusive ownership
Backup may continue, but patch 5 live Repair and Restore refuse to mutate recovery without exclusive ownership. Fix the reported permission or filesystem issue before retrying those actions.
Live Repair and Restore attempt to register WinRE Manager - Resume when a script path is available and staging checks pass. Its triggers are boot+1m and a one-shot at T+1h. Patch 5 centralizes retention around unresolved pending deployments: reading an unsafe record fails closed, and entering pending deployment arms retention until the actual registered destination and durable state are verified. Restore failure handling, the outer exception handler and unresolved owned-mount cleanup can also retain the task. finally combines that retention decision with the compiled [WinRECancelKeyProbe]::ShouldPersist Ctrl+C signal. A hard kill or reboot can leave the task registered without either signal because finally never runs. If registration or the Ctrl+C hook failed, the log names the missing protection; an interruption does not guarantee a task exists. See the retention contract.
The task is a per-run safety net, not machine state. Its presence indicates an interrupted Repair or Restore; its absence is the normal state after a clean completion. When present, the resume run re-invokes the production script’s default Repair action, which completes the operation from the checkpoint. Do not delete it manually unless you intend to abandon the interrupted operation.
v50 patch 3 resume-script staging design. The v50 patch 1 protected-path guard (which refused to register the task when the script directory granted any write-capable right to Everyone, BUILTIN\Users, Authenticated Users, or INTERACTIVE) and the v50 patch 3 first-revision three-path Test-PathTrustedForSystem check both shipped a false positive on every development checkout: any script running from a path a non-admin could write was refused, so an interrupted run had no automatic recovery hook. The final design stages the running script to C:\Recovery\OEM\Resume\WinRE.ps1 under an explicit DACL (SYSTEM and Administrators FullControl, inheritance disabled), byte-verifies the copy against the source, re-verifies the staged file and its directory with Test-PathTrustedForSystem, and registers the task against the staged copy. On clean terminal exit the staging directory is removed at the same point the task is unregistered. A self-staging case (the resume task firing and re-invoking the script from the staged path) is detected and short-circuited. The residual — a non-admin who modifies the running script before this elevated process stages it — is not a new exposure: the process is already executing that script elevated. Registration refusal is non-fatal: the repair pipeline proceeds without the self-healing hook, and the log names the failure reason (staging-directory creation, script copy, hash mismatch, or the final trust check).
Under $PSCommandPath-less invocation — gist bootstrap via Invoke-RestMethod | Invoke-Expression, or paste-into-console — the guard in Register-ResumeTask logs at INFO and does not register the task. This is by design: those invocation modes have no $PSCommandPath, and the guard skips the registration. A run initiated from such an invocation cannot be resumed by the task; the operator must re-run the script manually after an interruption.
The task profile is SYSTEM / highest run level, startup+1m and one-shot T+1h, StartWhenAvailable, battery-allowed, no idle requirement, network not required, 24-hour execution limit. The same profile as the primary scheduled task’s conservative settings, so a resume run behaves identically to a scheduled run for the purposes of the offline fallback and the fast-path gates.
Place WinRE.ps1 in a directory that:
SYSTEM can read. C:\ProgramData\OEM\ is the standard choice.C:\ProgramData\OEM\ with default ACLs is safe; do not use C:\Temp\.The script writes to C:\ProgramData\OEM\Logs\ for the log, checkpoint file, and lock file. SYSTEM can write there by default.
v50 patch 1 adds a machine-wide config file at C:\ProgramData\OEM\WinRE-Manager\manager.json; the v50 patch 3 release extends the trust check. The file holds the backup-root catalogue read by the Cleanup-Backups.ps1 helper, and any future durable setting. The v50 patch 1 form of the trust gate verified the ACL owner of the containing directory and its immediate parent (SYSTEM or Administrators). The v50 patch 3 form replaces this with the shared Test-PathTrustedForSystem helper: the ACL owner is SYSTEM or Administrators, no Allow ACE grants a modify-capable right to a principal outside SYSTEM, Administrators, or TrustedInstaller, and the config file itself is checked in addition to its containing directory and that directory’s parent. The v50 patch 4 form additionally skips InheritOnly ACEs: those apply only to children, not to the object being checked, and treating them as effective on the object itself is a false-positive source on the stock C:\ProgramData ACL, which carries an inherited CREATOR OWNER ACE with (OI)(CI)(IO)(F). CREATOR OWNER (S-1-3-0) and CREATOR GROUP (S-1-3-1) are deliberately not added to the trusted SID list — the fix is to skip ACEs that do not apply, not to trust their principals generally. The identical logic exists in three copies (WinRE.ps1’s Test-PathTrustedForSystem, Cleanup-Backups.ps1’s local copy, and the shared _T helper in WinRE-Manager.cmd’s elevated payload), a maintainer commitment recorded in CONTRIBUTING.md; any future change to the helper must land in all three. The WinRE.ps1 copy is field-exercised on the project’s ASUS test machine (2026-10-19); the Cleanup-Backups.ps1 and WinRE-Manager.cmd copies are byte-verified only. The modify-capable mask differs by object class (on a directory it is Delete | DeleteSubdirectoriesAndFiles | TakeOwnership | ChangePermissions; on a file it adds WriteData | AppendData). An untrusted, unreadable, or unparseable config is treated as absent and the caller falls back to the empty default. Two directory levels are checked, not one — the stock C:\ProgramData ACL grants Authenticated Users the ability to create subdirectories, and a directory created by a non-admin principal is owned by that principal; checking only the immediate parent is bypassable on a subsequent run by a delete-and-recreate swap. The file-level check closes a pre-creation attack a directory-only check would not: a non-admin who pre-created manager.json inside a SYSTEM-owned directory would pass a directory-only check but is refused by the file-level check, because the planted file is owned by the attacker, not SYSTEM. Writes are atomic via the existing Write-FileAtomically. The file is created on first successful -Action Backup; its absence is not an error and does not block a subsequent backup, restore, or cleanup.
The wrapper’s install option uses C:\ProgramData\OEM\WinRE-Manager\WinRE.ps1 as the stable install location and registers the task against that copy rather than against the operator’s local clone. Both C:\ProgramData\OEM\ and C:\ProgramData\OEM\WinRE-Manager\ have the same ACL properties for the purposes of the scheduled task.
The image workspace is where the script mounts, injects into, and exports the WinRE image during a full update. As of v45 patch 1, the workspace is chosen at run time from a set of eligible volumes rather than assumed to be C:\Temp\WinREWork.
The selector accepts only volumes that are:
ATA, SATA, NVMe, RAID, SAS, Spaces, Virtual, File Backed Virtual, SCM. As of v50 patch 2, SCSI is also accepted for the running OS volume only. A guest whose OS disk is on a virtual SCSI controller (common inside a Hyper-V VM) gets a usable workspace; a non-OS SCSI disk is still excluded because a host physical disk passed through to a guest can also report SCSI and the workspace holds temporary servicing files, not deletion targets.Recovery or WINRE.<volume>:\Temp or <volume>:\Temp\WinREWork.USB, SD/MMC, network, FireWire, Fibre Channel, unknown-bus disks, and reparse-point workspace paths are excluded even when Windows reports them as fixed.
$MinFreeSpaceGB.WIM_READY checkpoint exists in the recorded workspace. The WIM_READY flag is set at Step 4 after a verified dism /Export-Image. base.wim is deleted at that point to reclaim workspace capacity before partition planning.A run that cannot find any eligible volume above the floor defers with EXIT_WARNING before touching the machine. Free space on any eligible volume and re-run.
X:\Temp\WinREWork directories on eligible internal volumes. It never touches user files or arbitrary temporary directories elsewhere.The harness Option 1 diagnostic reports the eligible workspace candidates and their free space.
The Audit Mode guard runs after the elevation guard, after the program lock, and after the -Action Backup dispatcher; it is the first check the Repair and Restore paths perform. It runs before the hardware detection, before the manifest fetch, before the OEM pack resolution, before the DesiredStateId computation, before the pending-reboot block, and before the classifier. It reads a single registry value:
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Setup\State
→ ImageState (string)
If the value is absent, or if it is exactly IMAGE_STATE_COMPLETE, the guard passes and the script proceeds normally. Any other value causes a deferral.
During Audit Mode, OOBE, the sysprep generalize phase, and the sysprep specialize phase, Windows blocks reagentc /enable with ERROR_CANCELLED (0x4c7, 1223). This is not a bug in the script, and it is not related to the correctness of the deployed WIM or the state of the recovery partition. The OS refuses the call by design until the machine has reached a normal desktop.
The destructive partition work the script would otherwise perform on such a machine accomplishes nothing — the partition will be re-created on the next run anyway — and leaves a state file recording the deployment as complete. On the next run, the enable-only path fires because the state file matches and WinRE is still disabled, and it fails the same way. Without the guard, the machine loops forever, and the operator sees a fleet of machines that “deployed successfully” but never enabled WinRE.
Two additional defenses exist for the enable failure itself, in case the Audit Mode guard is somehow bypassed or the failure comes from a different source:
"failed" result or a "bitlocker" result — or when the target partition could not be prepared — it increments EnableFailureAttempts in the state file and exits EXIT_WARNING. It does not fall through to full update; the deployment is current and a rebuild would not change the outcome.EXIT_FATAL with an actionable message. The state file is left in place; the operator resolves the underlying cause and deletes C:\Recovery\OEM\winre_state.json to reset the counter.See exit-codes.md and troubleshooting.md for the full description.
The scheduled task does not need to be aware of the machine’s ImageState. The script handles it. But if you are deploying to a fleet of freshly imaged machines, be aware of the timing:
BootTrigger with a PT2M delay, a machine that reboots out of image but does not sign in for a day will exit EXIT_WARNING on every boot until a user reaches the desktop.EXIT_WARNING exits are cosmetic in this case; they will not loop, and they will not consume the enable-failure counter (the Audit Mode gate runs before the state file is even read).If you want to confirm the machine is ready to run before pushing the task, check ImageState on a representative image:
(Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Setup\State" -Name ImageState -ErrorAction SilentlyContinue).ImageState
A machine ready for deployment returns IMAGE_STATE_COMPLETE, or the command returns nothing because the SKU omits the key. Both are safe.
If the command returns any other value, the machine has not finished OOBE. Wait for a user to sign in, then let the scheduled task fire on the next weekly or boot trigger (or run the script manually).
Windows 11 24H2+ enables Device Encryption by default on hardware meeting TPM 2.0 and Secure Boot requirements. The relevant fact about Device Encryption for this project is that it can encrypt a newly created partition on the same disk, including a freshly created recovery partition, before the recovery type GUID and attributes can be applied to it. The partition then carries the default Basic Data type for a short window and can be claimed by the encryption service during it.
The v43 patch 5 (further revision 5) policy addresses this by acting on the volume reagentc will enable, not on the OS volume. Concretely:
reagentc /enable is called. Set-RecoveryPartitionReadyForWinRE prepares it: if the partition is already clean it returns immediately, otherwise it runs manage-bde -off against the partition and polls for completion at 5-second intervals up to a 300-second timeout. This is called on the enable-only path, the full-update path with an existing recovery partition, the full-update path with a newly created partition, and the pending-reboot repair path.VolumeStatus before deploying and defers unless it is FullyDecrypted. The script never modifies C:’s state. As of v44 patch 6, the destructive partition path does not gate on C:’s state — the dedicated-partition path’s success or failure depends on the partition geometry, not on C:’s encryption state. The path queries C:’s encryption state only to log it, and the log line explicitly records that C: encryption is not a veto for the dedicated-target path.New-Partition time. This closes the window between partition creation and Set-RecoveryPartitionAttributes during which a plain Basic Data partition could be claimed by the Device Encryption service.Suspend-BitLockerForWinRE was deleted. Suspension does not prevent Device Encryption from claiming new partitions — proven in the field — and it is useless for OS-fallback, where reagentc refuses regardless.The v43 patch 5 (further revision) design gated on C:’s BitLocker state at startup. It deferred any run where C: was not FullyDecrypted with Protection On. That design was correct in the sense that it prevented the Dell Latitude 3550 / HP ProBook 450 G10 failure mode, but it was over-broad: it deferred on the FullyEncrypted + Protection Off state, which is the normal state of every fresh Win11 local-account machine before a Microsoft account sign-in. The startup gate was deferring on the majority of the fleet.
The change was driven by a same-machine test on 2026-09-29. With C: in the FullyEncrypted + Protection Off state, reagentc /enable against a dedicated recovery partition succeeded while reagentc /enable against the OS volume failed on the same machine in the same session. That established that reagentc’s check is on the target volume. The policy was inverted accordingly: prepare the target; do not gate on C: except on the OS-fallback route, where the target is C:.
The scheduled task does not need to be aware of the machine’s encryption state. The script handles it. But three deployment-time facts are worth knowing:
FullyDecrypted. The log names the C: state and tells the operator what to do: complete decryption of C: (manage-bde -off C:) or wait for an in-progress decryption to finish. Actions that complete encryption, add a protector, or enable protection do not resolve the state — they make C: more protected, not less. This deferral does not consume the enable-failure counter.New-Partition or Format-Volume failure — the run falls through to OS-fallback. The OS-fallback gate then consults C: and defers cleanly if C: is encrypted. As of v45 patch 1 the shrink is no longer inside the destructive window: a failed pre-shrink returns Deferred with the old route preserved and never reaches OS-fallback, so the shrink case no longer produces this fall-through.If you are deploying to a fresh fleet and want the first run to succeed rather than defer on the OS-fallback route, wait until manage-bde -status C: shows Fully Decrypted before pushing the task. On a modern SSD, decrypting C: from a mid-encryption state typically takes 30–90 minutes.
The VMD hardware presence check determines which driver set the script selects. As of v44 patch 6 the check is fail-closed: if the PnP enumeration reports an error during the query, the run treats VMD presence as indeterminate rather than as absent, and defers with EXIT_WARNING before committing any state.
The reasoning: guessing “absent” on a machine that genuinely has VMD hardware would select a driver set that omits the VMD package, and the deployed WinRE would not be able to see the OS disk. An empty device list from an errored enumeration is not evidence of absence. The cost of a deferral is one pipeline run; the cost of guessing wrong is a machine with a non-functional recovery environment.
A run that defers this way leaves the machine unchanged: no WIM deployed, no partition touched, no reagentc call made. The next scheduled run retries the enumeration; a transient PnP service issue is the most likely cause. If the deferral fires repeatedly, resolve the underlying PnP service issue — the deferral is a protective stop, not a degraded-success.
The v49 release adds three gates that narrow what the pipeline will deploy. Each is described in full in driver-injection.md; this section covers the deployment-time implications.
Every source considered for servicing is classified as Manager-Owned, Manager-Lineage, Foreign-No-Drivers or Foreign-With-Drivers. The last class is preserved unchanged using -Discard. Patch 5 separately assesses dedicated capacity and can relocate preserved bytes after a read-only applicability check. An accepted foreign hash remains separate from CurrentImageHash; it does not bypass layout checks or establish recovery-boot success.
Operational consequence: a machine whose registered WinRE was populated by a vendor tool with third-party drivers now deploys with those drivers instead of the manager’s recipe. This is the intended v49 behavior; the ASUS-incident field case is the reason it exists. If the operator wants the manager’s recipe applied, the source must be replaced with one that classifies as Manager-Owned, Manager-Lineage, or Foreign-No-Drivers — typically by using the LKG copy or the GitHub cold-start source.
The classification is not operator-configurable in v49; it is derived from the source’s actual driver set (a third-party driver count of zero vs. non-zero) plus two positive-ownership signals: a staged-source hash exact-match against state.CurrentImageHash (Manager-Owned) and a valid provenance marker whose LineageId matches the state file’s (Manager-Lineage).
After injection completes and before ResetBase, the manager compares each storage-class driver in the final image against the pre-strip inventory, matched by INF basename. If any post-injection driver would be older than the source’s version of the same basename, the entire candidate is discarded — not just the offending driver — the mounted image is dismounted with -Discard, the source is preserved, the state file records ForeignSourceAcceptedHash, and the run exits EXIT_WARNING. The whole source is preserved rather than partially normalized.
Operational consequence: the downgraded candidate is never deployed. In patch 5, the preserved original can still be relocated to an adequate dedicated recovery partition. Subsequent fast paths require a verified adequate dedicated route as well as the accepted source hash.
The log names each detected downgrade — the driver’s INF basename, the source version, and the candidate version.
The gate runs inside Step 3, after injection is confirmed complete and after the never-downgrade check, before ResetBase and before the dismount. It is the last refusal before the WIM is written to the active route, but its position is inside Step 3 — the deploy step runs later in the pipeline, and a candidate that fails the gate is dismounted with -Discard before the pipeline reaches the deploy stage. The manager verifies that every present SCSIAdapter-class device on the machine has at least one INF in the candidate image whose HardwareID or CompatibleID prefix-matches one of the device’s IDs. A candidate that leaves any controller unmatched is refused rather than deployed.
Operational consequence: a machine whose candidate image does not contain a driver for its actual storage controller defers with EXIT_WARNING rather than receiving a candidate with no driver. The gate is the last refusal before deployment; it was added after the ASUS-incident field case. It rejected the first Hyper-V test candidate before partition mutation, exposing the VMBUS parser omission; corrected deployment and recovery boot were subsequently verified. No refusal on a physical machine has been recorded.
If a canary machine exits 2 with the applicability gate’s refusal, capture the full log and the harness Option 1 “Storage controllers” block (v28) — the machine’s controller IDs are what the maintainer needs to update the manifest’s VMD patterns or the OEM pack resolution.
A self-hosted manifest whose requiredDevices patterns omit a controller present on your fleet, or a self-hosted OEM pack whose INFs do not cover your fleet’s controllers, will cause the applicability gate to refuse the candidate on the affected machines. Keep both complete for the hardware you deploy to. The v49 pipeline does not add new external URLs; it only reads the manifest and pack content differently than v47/v48 did.
LocalInputsId added in v48 patch 1; v49 gates run offline as well)The script’s network calls — the driver manifest fetch, the OEM map fetches, and the base WIM download — each default to a 15-second per-call timeout. The timeout applies to each individual request, not to the aggregate; the retry loops (2 attempts for the manifest, 3 for the OEM pack download) can multiply it. Before v44 patch 5, an offline machine would hang for over 10 minutes across the aggregate of the default 100-second timeouts before failing. That is now capped at roughly 90 seconds in the fully-offline case, dominated by the fixed sleeps in the retry loops rather than by the network timeouts.
More importantly, v44 patch 5 adds an offline fallback for the manifest fetch. The behavior depends on the state file’s contents.
The script reads the state file at C:\Recovery\OEM\winre_state.json and trusts its stored DesiredStateId directly. It does not recompute the ID from cached inputs — recomputing would require the OEM pack version, which is resolved from the OEM map, another gist on the same unavailable network.
The local safety checks remain fully enforced and do not depend on the manifest. Under v47, the fast-path conditions the offline path validates are the same as the online path:
Enabled.DesiredStateId matches the stored value (used directly; the DSI is not recomputed offline).Version + SPBuild) matches the state file’s DeployedWinREMetadata anchor, and no force-upgrade, driver-version change, or missing-anchor condition applies.LocalInputsId matches the current locally-computable inputs (v48 patch 1). A stored value of $null (a state file predating v48 patch 1) skips the check with a WARN.UsedOSFallback = $true in the state file and the active location on the OS partition.The v49 pipeline refinements — source-ownership classification, never-downgrade check, storage-applicability gate — run inside the full-update path, which the offline fallback does not reach. They do not add new offline-path conditions. The native-boot VHDX fail-closed gate runs as a startup refusal on all paths, including offline, and a VHDX-boot machine defers before the offline fallback is engaged.
If all pass, the script takes the fast path, logs Offline fallback: using state file's stored DesiredStateId <id>, verifies the machine is healthy, and exits EXIT_WARNING (code 2) because $Script:offlineFallback = $true is set. The exit code is a degraded-success signal, not a failure. The machine is unchanged. Total runtime is under 90 seconds.
The v46 → v47 transition on offline machines. A v46-or-earlier state file lacks DeployedWinREMetadata. Its absence forces $needInject = $true regardless of network state, and the offline guard then fires: the machine needs a full update, but the live manifest is required for that, so the run exits EXIT_WARNING without further work. From the second v47 run onward, the state file has the anchor written by the first successful online run, and the offline fast path can fire normally. The one-time cost of the v47 migration on offline machines is therefore: the first scheduled v47 run must happen while the machine can reach the driver manifest.
The v48 → v49 transition on offline machines. The v49 ScriptVersion bump changes the SCRIPT component of the DesiredStateId, but on the offline fallback path the state file’s own DesiredStateId is used as-is (the DSI is not recomputed offline), so a v48 state file is accepted on the offline path and the fast path can fire. The run exits EXIT_WARNING because $Script:offlineFallback is set, not because a full update was forced. The v49 pipeline gates (source-ownership classification, never-downgrade check, storage-applicability gate) are not exercised on that first offline run; they are exercised on the next run with network, which recomputes the DSI and forces the v49 full-update pass. This is a deliberate consequence of the offline fallback’s “use the stored DSI directly” design: the offline path prioritizes a fast-path validation of a machine whose local state is trusted, and defers the v49 recipe change to the first online run.
On the next scheduled run with network, the script performs a full manifest fetch, detects any hardware drift that occurred while offline (a CPU swap, a BIOS update that flipped VMD, a motherboard replacement), and either takes the fast path (if no drift) or forces a rebuild (if drift).
The v48 patch 1 LocalInputsId field closes the offline hardware-drift residual. The state file now records a hash over the three deployment inputs observable on the local machine without a network fetch: hardware identity (Manufacturer|Model|MachineType), OS build, and CPU vendor/generation. VMD presence is deliberately excluded because its detection depends on the manifest’s requiredDevices patterns, which is precisely the input the offline fallback does not have. On the offline fallback path, the run recomputes the hash from the current machine and compares it against the stored value; a mismatch defers with EXIT_WARNING (Offline fallback: stored LocalInputsId <hash> does not match the current locally-computable inputs <hash>) rather than trusting a stored DesiredStateId that describes a machine whose hardware or OS has since changed. A VMD flip is not caught by LocalInputsId: VMD is a BIOS-configurable setting that can be toggled independently of the hardware, so HW and CPU do not capture it, and the hash deliberately excludes VMD because its detection needs the manifest. A machine whose VMD state changed while offline could take the fast path with a stale DesiredStateId — a documented residual of the offline fallback.
If the state file indicates a full update is needed (metadata drift, force-upgrade, driver version drift, or a locally-detected input change), the script cannot proceed offline — a full update requires the live manifest to resolve the driver set. It logs:
Offline fallback: the machine requires a full update (state file is stale or unhealthy), but the driver manifest is unavailable. Cannot proceed without a live manifest. Will retry on the next scheduled run when the network is available.
and exits EXIT_WARNING. No WIM is deployed, no partition is touched, WinRE is not disabled, no state file is written or modified. The next scheduled run with network completes the work.
A first deployment on a fresh machine requires the live manifest to compute the initial DesiredStateId. The script logs:
Driver manifest unavailable and no state file exists - a live manifest is required for the first deployment on this machine.
and throws. The outer catch logs FATAL ERROR: … and exits EXIT_FATAL (code 3). The machine retries on the next scheduled run when the network is available. No state-modifying action is attempted before the throw.
Because the offline fallback makes an offline scheduled run useful, the recommended task XML sets RunOnlyIfNetworkAvailable = false (see the XML above). With true, the task would not fire when the network is down, so the fallback would only help manual invocations — not the scheduled path where the machine actually needs it.
The scheduled task’s StartWhenAvailable = true continues to handle missed triggers after a cold boot. Combined with the offline fallback, a machine that reboots offline and misses its weekly window will still take a fast-path validation run on the next opportunity and exit EXIT_WARNING, then complete normally on the next run with network.
See exit-codes.md and troubleshooting.md for the full offline exit-code discussion.
The v49 release adds two standalone actions to the production script:
-Action Backup -BackupPath <dir> — captures a byte-for-byte copy of the currently registered WinRE WIM plus a sidecar backup.json recording the source hash, size, and DISM servicing metadata.-Action Restore -BackupPath <dir> — writes a previously captured WIM back to the currently registered route transactionally.Both actions are exposed by the WinRE-Manager.cmd wrapper: menu option 1 — Back up current WinRE in the SAFETY section, and menu option 8 — Restore WinRE from backup in the RECOVERY section. As of v50 patch 1 both the [8] Restore entry and the [C] Cleanup entry are shown unconditionally; the v49 patch 2 behaviour that hid them when no default-location backup existed was reversed because it removed the operator’s only path to the restore screen when a backup existed at a non-default location. The screens themselves now explain when no backup exists: Cleanup-Backups.ps1 reports No backup found under the default location and exits cleanly, and the restore screen requires an explicit path rather than defaulting to a nonexistent one. The HIDE_BACKUP_ACTIONS_WHEN_NONE toggle that existed in v49 patch 2 is removed; always-show is now the only behaviour. Once reached, the restore screen accepts any directory containing both files — including one on an external disk.
Backup is non-destructive. It does not rebuild, replace, or reconfigure the active WinRE route, and it does not write to the state file. It may temporarily assign a drive letter in order to access a WIM registered through a GLOBALROOT/volume path, and cleans the letter up under the existing temporary-drive-letter machinery. A backup operation exits EXIT_SUCCESS when both the WIM copy and the sidecar backup.json are written and verified; it exits EXIT_WARNING when the WIM copy and hash verification succeed but the sidecar write fails, because the operator needs to know the backup directory is missing its metadata. (The backup WIM itself remains usable for a subsequent restore; the sidecar is metadata only.)
Restore is transactional. It validates the backup, resolves the current registered route, handles dedicated and OS-fallback targets, uses the existing deployment machinery, re-registers WinRE, and re-enables it. Restore does not create a new partition or invent a replacement route — a usable current WinRE route must already exist. The operator is required to type RESTORE to confirm.
Restore exits. A clean restore exits EXIT_SUCCESS (or EXIT_REBOOT_REQUIRED if reagentc /enable schedules the registration for the next reboot). The three mid-transformation failure paths — the WIM-deployment failure when the re-enable attempt after the failure does not return ok (added in v50 patch 3), /setreimage failing after the WIM has been replaced, or /enable returning failed/bitlocker after the WIM is in place — all three preserve the temporary WinRE Manager - Resume task so the operation is resumed on the next boot or within the hour. The /setreimage failure exits EXIT_FATAL; the /enable failure exits EXIT_WARNING. A WIM-replacement failure that reaches the rollback branch exits EXIT_FATAL.
Fleet operators who use the scheduled task do not normally invoke these actions. They are exposed by the wrapper for a single-machine operator or a technician doing manual intervention. A fleet operator who needs to run a backup from an orchestration tool can invoke WinRE.ps1 -Action Backup -BackupPath <dir> directly; the action is a standalone command, not a pipeline stage.
The v44 patch 1, v45 patch 1, v46 patch 1, v47 patch 1, v48 patch 1, and v49 revisions each bump ScriptVersion, change the SCRIPT component of the DesiredStateId, and force one full-update pass per managed machine on the next scheduled run. The roll-out behaviour of each is documented below.
The v44 patch 1 revision changes the DesiredStateId inputs (adding CPU vendor/generation and VMD presence) and therefore bumps ScriptVersion from 43 to 44. The effect on a managed fleet is a one-time full-update pass per machine on the next scheduled run.
Concretely, on the first run after the update, every machine will:
DesiredStateId.needInject = $true, and take the full-update path.On a healthy NVMe laptop this is roughly 3–5 minutes of I/O and CPU. Machines with a suitable existing recovery partition re-use it; no partition work occurs on healthy machines. This is the intended behaviour and the reason the Migration Note in CHANGELOG.md is present.
Two cases that are handled cleanly without operator attention:
PendingReboot = true. The DSI mismatch is detected before the pending-reboot block runs, so the full-update path executes rather than the pending-reboot repair path. No machine is lost.EnableFailureAttempts >= 3). The DSI mismatch makes the state file stale before the loop-breaker check runs, so those machines get one fresh attempt under the new ID. If the underlying cause is resolved, they recover; if not, they re-enter the loop-breaker on the fourth fresh attempt.Plan for the v44 patch 1 rollout the same way you would plan for a manifest-version bump: brief the operator community, expect the first run after the update to be slower than usual, and check the log on a canary machine to confirm the full-update path executed and the state file was rewritten under the new ID.
Change $ScriptVersion back to 43, revert the Get-DesiredStateId $parts array, and restore the previous Get-HardwareObject if the manufacturer normalisation differed. No data is lost; another fleet-wide rebuild occurs on the next run.
The v45 patch 1 revision is the shrink-first redesign of the destructive partition path. It bumps ScriptVersion from 44 to 45, which changes the SCRIPT component of the DesiredStateId and forces one full-update pass per managed machine on the next scheduled run — exactly the same shape as the v44 patch 1 migration, and for the same reason: the DSI is the deployment-identity fingerprint, and any change to the inputs that determine the deployed artifact is a version boundary.
The v45 pass is not slower on a healthy machine than any other full-update pass. The reorder moves the shrink into the reversible window; the total work is the same. Machines with a suitable existing recovery partition reuse it and perform no destructive work.
Concretely, on the first run after the update, every machine will:
DesiredStateId (with SCRIPT=45).needInject = $true, and take the full-update path.Two cases handled without operator attention:
C:\Recovery\OEM\winre_partition_deferred.json. The marker was introduced in v45 patch 1 and is keyed by DesiredStateId; it is honored only when the current run computes the same DSI. No operator action is needed on the v44→v45 transition, because no v44-era marker can exist.PendingReboot = true or EnableFailureAttempts >= 3. Handled the same way as in the v44 patch 1 migration: the DSI mismatch is detected before the pending-reboot and loop-breaker blocks.Change $ScriptVersion back to 44. The state file written under the v45 DSI becomes stale, the next run takes the full-update path under the older behavior, and the pipeline falls back to the pre-v45 destructive sequence. No data is lost; another fleet-wide rebuild occurs on the next run.
The v46 patch 1 revision clamps tailEnd to diskSize − 1 MiB before aligning in Get-PartitionPlan. It bumps ScriptVersion from 45 to 46, which changes the SCRIPT component of the DesiredStateId and forces one full-update pass per managed machine on the next scheduled run — the same shape as the v44 patch 1 and v45 patch 1 migrations.
The v46 pass is not slower on a healthy machine than any other full-update pass. The clamp changes the plan computation only when the last partition on the disk ends at diskSize (equivalently, at the disk-end reserve boundary); on every other layout, the plan is identical to v45’s. Machines with a suitable existing recovery partition reuse it and perform no destructive work.
The distinguishing behaviour of this migration is what happens to machines that v45 patch 1 left in OS-fallback because of the plan-clamp bug. Under v45, the plan was rejected after the old recovery partition had already been deleted, and the machine fell back to OS-fallback. The state file recorded the failing DesiredStateId and was accepted on every subsequent run, so the machine stayed in OS-fallback and did not retry. The v46 patch 1 ScriptVersion bump clears that state automatically: the state file is stale under the new DSI, the next run takes the full-update path, and the plan-clamp fix makes the plan valid on the same layout v45 rejected. The machine reaches DEDICATED on the first full-update pass.
Concretely, on the first run after the update, every machine will:
DesiredStateId (with SCRIPT=46).needInject = $true, and take the full-update path.Two cases handled without operator attention:
C:\Recovery\OEM\winre_partition_deferred.json. The marker is keyed by DesiredStateId; it is stale under the v46 DSI and is cleared on read by Read-PartitionDeferral. No operator action is needed.Change $ScriptVersion back to 45. The state file written under the v46 DSI becomes stale, the next run takes the full-update path under v45’s behavior, and the pipeline is once again vulnerable to the plan-clamp bug on machines whose last partition ends at diskSize. No data is lost; another fleet-wide rebuild occurs on the next run.
The v47 patch 1 revision introduces the third-party driver strip stage and rewrites several other rebuild-path elements. It bumps ScriptVersion from 46 to 47, which changes the SCRIPT component of the DesiredStateId and forces one full-update pass per managed machine on the next scheduled run — the same shape as the v44 patch 1, v45 patch 1, and v46 patch 1 migrations.
The v47 release is architecturally different from the earlier ScriptVersion bumps. v44 added DSI fields; v45 and v46 patch 1 each corrected a specific bug that had left machines stuck. v47 patch 1 changes what a rebuild produces, not just how a rebuild is triggered: the mounted image is stripped to zero third-party drivers, proven by re-enumeration, and only then is the current driver recipe injected. The deployed WIM bytes therefore differ from v46’s on the same inputs. The version bump is the mechanism by which the fleet converges on the strip-normalized driver set.
The v47 pass is not materially slower on a healthy machine than any other full-update pass. The strip stage on an already-clean image is a no-op — the ASUS field run logged Strip: image already has zero third-party drivers in under a second. On a machine whose registered image carries the OEM/VMD drivers from an earlier WinRE Manager cycle, the strip removes them and the current recipe is injected; the total time depends on the driver set size, not on the strip itself.
The distinguishing property of this migration is the metadata anchor. Every machine’s first v47 run writes a DeployedWinREMetadata field to the state file — the DISM servicing metadata (Version + SPBuild) of the WIM that was actually deployed. The field is the anchor the v47 drift detector compares against on every subsequent run. A machine whose state file lacks the anchor (all v46-or-earlier state files) forces a rebuild regardless of whether any other input changed; a machine whose state file has the anchor is evaluated against it.
Concretely, on the first run after the update, every machine will:
DesiredStateId (with SCRIPT=47).needInject = $true, and take the full-update path.DeployedWinREMetadata anchor.Three cases handled without operator attention:
PendingReboot = true or EnableFailureAttempts >= 3. As in every prior migration: the DSI mismatch is detected before the pending-reboot and loop-breaker blocks, so the full-update path executes and the counters are reset.C:\Recovery\OEM\winre_partition_deferred.json. The marker is keyed by DesiredStateId; it is stale under the v47 DSI and is cleared on read by Read-PartitionDeferral.Version or SPBuild. The metadata comparison would fire on the second v47 run, but is subsumed by the DSI mismatch on the first — the rebuild happens regardless.The offline-migration case is one step longer. On a machine whose first v47 run is offline, the state file lacks the anchor, $needInject is forced to $true, and the offline guard fires — the run exits EXIT_WARNING without a rebuild. The first successful online run writes the anchor; from the second v47 run onward, the offline fast path works normally. If a machine in your fleet runs offline for an extended period, expect its first online v47 run to be the one that writes the anchor.
Change $ScriptVersion back to 46 and revert the strip stage, the three-source selection logic, the race detector, and the metadata-drift changes. The state file written under the v47 DSI becomes stale, the next run takes the full-update path under v46’s behavior, and the strip-normalized image is replaced with a lineage-seeded one. The DeployedWinREMetadata field becomes inert on rollback — it is read only by the v47 drift detector. No data is lost; another fleet-wide rebuild occurs on the next run.
The v48 patch 1 revision is the largest single architectural change to the manager since v43. It bundles five distinct changes: intervening-partition handling, the architecture gate, the LocalInputsId state-file field, LKG-by-hash at any discovered recovery location, and transactional WIM replacement. It bumps ScriptVersion from 47 to 48, which changes the SCRIPT component of the DesiredStateId and forces one full-update pass per managed machine on the next scheduled run — the same shape as the v44 patch 1, v45 patch 1, v46 patch 1, and v47 patch 1 migrations.
The v48 pass is not materially slower on a healthy machine than any other full-update pass. On the ordinary non-intervening path, the pre-shrink target is C: and the pipeline is unchanged from v47; the transactional WIM replacement adds one hash of the existing target WIM (roughly 1-3 seconds on an NVMe) before the delete-then-copy sequence. On the intervening-anchor path, the pre-shrink target is the anchor instead of C:, and the anchor resize adds roughly one additional minute of I/O on a 720 GiB data partition.
Concretely, on the first run after the update, every machine will:
DesiredStateId (with SCRIPT=48).needInject = $true, and take the full-update path.EXIT_WARNING).LocalInputsId in the state file on the state write at the end of the run.C: | D: | Recovery), D: is the resize target and is validated before any mutation.LocalInputsId, and (as in v47) the DeployedWinREMetadata anchor.Three cases handled without operator attention:
PendingReboot = true or EnableFailureAttempts >= 3. The DSI mismatch is detected before the pending-reboot and loop-breaker blocks, so the full-update path executes and the counters are reset.C:\Recovery\OEM\winre_partition_deferred.json. The marker is keyed by DesiredStateId; it is stale under the v48 DSI and is cleared on read by Read-PartitionDeferral.Two cases where the v48 pipeline defers where v47 deferred differently:
intervening anchor is N MiB smaller than the plan requires ...). Under v47, the same layout would have produced the separation rejection because the intervening partition was in the way. Both reject; the v48 message names a different reason and offers the same deferral outcome. The operator path is unchanged: resolve the layout (extend the anchor, or reduce the desired recovery partition size), then delete the state file and deferral marker to force a retry. See troubleshooting.md.C: | D: | E: | Recovery layout still rejects, as it did under v47. The v48 message names the intervening partitions with Format-PartitionRef enrichment.Change $ScriptVersion back to 47 and revert the five bundled changes: the intervening-anchor plan logic, the architecture gate, the LocalInputsId computation and its state-file field, the LKG-by-hash discovery scan in Get-LKGWinREImagePath, and the transactional WIM replacement. The state file written under the v48 DSI becomes stale, the next run takes the full-update path under v47’s behavior, and the LocalInputsId field becomes inert. No data is lost; another fleet-wide rebuild occurs on the next run.
The v49 revision is the largest single release since v48. It bundles four distinct changes to the production pipeline (three inside the full-update path plus one startup refusal), two standalone backup and restore actions, a temporary crash-recovery scheduled task, and a rewritten interactive wrapper:
Foreign-With-Drivers source is preserved as-is rather than stripped and re-injected. This narrows the v47 strip-and-reinject policy to sources the manager itself deployed or in-box images with no third-party drivers.-Discard, the source is preserved, the state file records ForeignSourceAcceptedHash, and the run exits EXIT_WARNING.-Discard, and deferred.File Backed Virtual and at least one other disk is on a physical bus — the native-boot VHD/VHDX topology, where the running OS disk is a VHD/VHDX stored on a host physical disk. A hypervisor guest whose entire storage stack is virtual is not refused.-Action Backup and -Action Restore are standalone commands that do not participate in the repair pipeline.WinRE Manager - Resume task that fires at boot+1m and one-shot at T+1h; deleted on clean completion, preserved on interruption.v49 bumps ScriptVersion from 48 to 49, which changes the SCRIPT component of the DesiredStateId and forces one full-update pass per managed machine on the next scheduled run — the same shape as the prior ScriptVersion-bump migrations.
The v49 pass is not materially slower on a healthy machine than any other full-update pass. The source-ownership classification is a set membership test against the source WIM’s driver inventory (already enumerated by the v47 strip stage on the manager-owned path); the never-downgrade check is a version comparison against the same inventory; the applicability gate is a set membership test against the machine’s storage controllers. On a machine whose source and manifest are unchanged from v48, the pass produces the same output as v48’s pass did; the gates’ decisions are the same.
Concretely, on the first run after the update, every machine will:
DesiredStateId (with SCRIPT=49).needInject = $true, and take the full-update path.-Action Backup dispatcher, Audit Mode guard (v43 patch 5, further revision), temporary resume-task registration (v49), -Action Restore dispatcher, hardware and architecture resolution, architecture gate (v48 patch 1), native-boot VHDX fail-closed gate (v49). On a Repair run the two action dispatchers do not fire and execution continues past them. Of these, the elevation guard, the Audit Mode guard, the architecture gate, and the VHDX gate can exit EXIT_WARNING (or EXIT_FATAL for the elevation guard) before any further work.Foreign-With-Drivers source: strip to zero third-party drivers, then inject the current OEM and VMD recipe subject to the never-downgrade check.
On a Foreign-With-Drivers source: skip the strip and injection; the source is preserved as-is.LocalInputsId, and the DeployedWinREMetadata anchor.Three cases handled without operator attention:
PendingReboot = true or EnableFailureAttempts >= 3. The DSI mismatch is detected before the pending-reboot and loop-breaker blocks, so the full-update path executes and the counters are reset.C:\Recovery\OEM\winre_partition_deferred.json. The marker is keyed by DesiredStateId; it is stale under the v49 DSI and is cleared on read by Read-PartitionDeferral.One case where the v49 pipeline defers where v48 deferred differently:
HardwareID or CompatibleID now defers with EXIT_WARNING where v48 would have deployed. This gate has never fired in the field. If a canary produces the refusal, capture the full log and the harness Option 1 “Storage controllers” block (v28).The v49 ScriptVersion bump adds two optional fields to the state-file schema: ForeignSourceAcceptedHash (set when a Foreign-With-Drivers source is preserved, so subsequent runs recognize the accepted foreign source) and LineageId (the persistent lineage identifier written into the provenance marker and carried forward across runs). Both are absent on state files written by v48 or earlier; their absence is handled as any other missing field. The fields added by v47 patch 1 (DeployedWinREMetadata) and v48 patch 1 (LocalInputsId) are unchanged. The backup and restore actions write a backup.json sidecar in the operator-supplied backup directory; they do not touch the state file. The temporary resume task is a separate scheduled task, not a state-file field.
Change $ScriptVersion back to 48 and revert the v49 changes: the source-ownership classification, the never-downgrade storage-driver check, the pre-deployment storage-applicability gate, the native-boot VHDX fail-closed gate, the backup and restore actions, and the temporary resume task. The rewritten wrapper (WinRE-Manager.cmd) is independent of WinRE.ps1’s version and can be left in place; the wrapper’s install option still registers the task against the stable C:\ProgramData\OEM\WinRE-Manager\WinRE.ps1 copy. The state file written under the v49 DSI becomes stale, the next run takes the full-update path under v48’s behavior, and the fleet converges onto the v48 pipeline. No data is lost; another fleet-wide rebuild occurs on the next run.
The v50 patch 1 revision bumps ScriptVersion from 49 to 50, which changes the SCRIPT component of the DesiredStateId and forces one full-update pass per managed machine on the next scheduled run. Unlike the v47/v48/v49 migrations, the pipeline’s decisions on an unchanged machine are the same as they were under v49; the version boundary exists to trigger the ownership-migration hash bridge (below) and to exercise the newly added manager config helpers, resume-task protected-path guard, and empty-parent cleanup on every machine.
The ownership-migration hash bridge. Without the bridge, the first v50 run on a machine whose state file was written by v49 would read the stale state file, reject it as DSI-mismatched, and classify its own prior deployment as Foreign-With-Drivers — preserving a source the v49 manager had deployed and normalized. The v50 Get-SourceOwnershipClassification takes -HistoricalImageHash and -HistoricalLineageId; the classifier matches the staged source hash against the current state.CurrentImageHash or a historical CurrentImageHash read via the new Get-StaleWinREStateFields helper. The historical read is used only by the source-ownership classifier and does not make the stale state operationally authoritative. Get-StaleWinREStateImageHash is replaced by Get-StaleWinREStateFields.
Concretely, on the first run after the update, every machine will:
DesiredStateId (with SCRIPT=50).needInject = $true, take the full-update path.CurrentImageHash and LineageId.state.CurrentImageHash classifies as Manager-Owned and the pipeline proceeds as normal.Cases handled without operator attention: PendingReboot = true or EnableFailureAttempts >= 3 (the DSI mismatch fires before the pending-reboot and loop-breaker blocks); a v49 deferral marker (keyed by DesiredStateId; stale under the v50 DSI, cleared on read); a v49 Step 3 or Step 4 checkpoint (bound to the v49 source hash — honored if the source is still available with the same bytes, else invalidated and the run rebuilds from Step 2).
The v50 patch 1 additions beyond the DSI bump. The release adds a machine-wide manager config file at C:\ProgramData\OEM\WinRE-Manager\manager.json; a two-level ownership check on the config directory; a resume-task protected-path guard; a destination-volume free-space preflight on backup; UNC resolution for mapped-drive backup paths; empty-parent cleanup in production and in Cleanup-Backups.ps1; an aggregate summary line for stray-recovery-partition cleanup; unconditional [8] and [C] entries in the wrapper menu; and a Check-Update.ps1 revision that removes the local cache and switches the primary source to the GitHub Releases API. Only the DSI bump is a state-file-affecting change.
Change $ScriptVersion back to 49. The state file written under the v50 DSI becomes stale, the next run takes the full-update path under v49’s behavior. The manager config file at C:\ProgramData\OEM\WinRE-Manager\manager.json becomes inert on rollback — it is read only by v50 additions. No data is lost; another fleet-wide rebuild occurs on the next run.
Patch 5 retains ScriptVersion = 50 and the seven DSI inputs, but fresh layout checks change which machines can take a healthy fast path. An OS-fallback route or an inadequate dedicated partition is assessed even when its state and accepted image hash still match. A current manager-owned image needing only layout repair can be copied unchanged. Foreign preservation does not grant manager ownership.
The pending candidate is staged under %ProgramData%\OEM\WinRE-Manager\PendingDeployment\pending.wim, with a trusted pending-deployment.json in the manager directory. Staging requires the candidate WIM size plus 32 MiB available on the OS volume. The later shrink/free-space assessment uses capacity after staging. Ordinary servicing scratch cleanup and DSI mismatch do not remove an unresolved candidate.
During canary testing, distinguish adequate dedicated, undersized dedicated and OS-fallback machines; distinguish preservation from normal servicing. Collect the selected disposition, layout assessment, expected hash checks, final route and any pending record. If actual creation failure reaches verified last-resort OS-fallback, expect warning and retained operation material, not convergence or record retirement. The supplied v50.4 successful logs are baseline evidence. Patch 5’s real partition and interruption transitions still require the validation matrix.
Resolve an unfinished pending deployment before reverting to a script that does not understand its record. Keep its protected WIM, record, logs and an appropriate disk backup until the actual route is verified. Installing v50.4 again does not reconstruct deleted partitions or reverse a successful resize.
The partition placement policy and the 2048 MiB protection remain unchanged in patch 5. The proposed v51 rightmost-data-partition/disk-tail placement is a separate release decision; reverting to patch 5 after v51 also does not undo v51’s physical partition changes.
The v44 patches 2 through 8, the v46 patch 2 additions, the v47 patches 2 and 3, the v48 patch 2, the v49 patch 2, and the v50 patch 2 do not bump ScriptVersion and do not change the DesiredStateId. They apply to every subsequent run without a state-file action. A machine that is already healthy continues to take the fast path. A machine that was mid-deployment when the patch rolled out continues from where it was — the checkpoint and state-file schemas are unchanged.
The v47 patch 2 revision is also not a fleet-wide rebuild: it does not bump ScriptVersion, and its only DSI-value change is a one-time event on a narrow machine class (machines with a padded Win32_ComputerSystemProduct.Version field). It is documented under ### v47 patch 2 specifically below. The v47 patch 1 revision is not in this list; it bumps ScriptVersion and is documented under “v47 patch 1 migration” above.
The v48 patch 2 revision is also not a fleet-wide rebuild: it does not bump ScriptVersion and does not change the DesiredStateId. It adds the fail-fast elevation guard, a source-WIM hash cache that closes a pre-existing enable-only fallthrough path, a resize-target resynchronisation fix on the extension-failure fallback path (the D1 fix), and several cosmetic log and comment corrections. On a machine that ran v48 patch 1, the patch 2 build takes the fast path unchanged; the only observable difference is the startup banner and, on an unelevated launch, the millisecond refusal instead of a delayed Mount-WindowsImage failure. Documented under ### v48 patch 2 specifically below.
dism /cleanup-image /StartComponentCleanup /ResetBase to the full-update pipeline; the size reduction materialises on the next natural rebuild, not immediately.Ensure-AdequateRecoveryPartition (removed in v44 patch 6) and a base.wim cleanup on the injection-failure abort branch (retained).C:\ProgramData\OEM\Logs\WinREManager.lock, so a second concurrent instance fails fast with EXIT_WARNING instead of colliding at Step 2.Find-SuitableRecoveryPartition. It also clears the VMD extraction directory before each extraction, and adds C:’s actual encryption state to the destructive-replacement WARN (diagnostic only; the decision to proceed is unchanged).Get-Partition -DiskNumber calls in Get-RecoveryPartitions against the empty-disk read that throws CmdletizationQuery_NotFound_DiskNumber on machines with an SD/MMC card reader. It also applies four post-review hardenings of Ensure-AdequateRecoveryPartition — the pre-deletion resolver guard, the extension-fallback bucket cap, the layout-assertion fail-closed branch, and the deletion-failure partial-rollback reporting. The build-logging values do not enter the DesiredStateId; the read guard silences a cosmetic error; the four hardenings change only the failure behaviour of the destructive sequence.Format-PartitionRef to the seven partition-identity plan-rejection reasons, so each reason now names the offending partition (disk number, partition number, size, label, type code); adds Remove-WindowsDriver and BusType to the harness parser self-test; makes -NonInteractive exit non-zero on any FAIL; guards the Lenovo-pack call on vendor; and adds the Compare-WimServicingMetadata harness mirror with an eight-case regression test. It does not change ScriptVersion or the DesiredStateId.ScriptVersion and does not change the DesiredStateId. The elevation guard refuses an unelevated launch in milliseconds; on an elevated launch the behavior is unchanged. The source-WIM hash cache closes a pre-existing enable-only fallthrough path where the state file would not be written because the source WIM became inaccessible after the temporary drive letter was removed..NOTES never-downgrade wording correction, two new wrapper helper scripts (Check-Update.ps1, Cleanup-Backups.ps1), three conditionally-visible wrapper menu entries, the wrapper’s child-process DryRun runner, and the wrapper’s -Wait on the elevated launcher. It does not bump ScriptVersion and does not change the DesiredStateId. The fail-open corrections are code-review fixes on error paths and cannot be exercised by a happy-path run; the wrapper changes need a canary smoke test.Win10/ to Win10/x64/), adds a non-OS-disk sweep suppression boundary in Remove-StrayRecoveryPartitions (with a new Test-RunningInVirtualMachine helper and a File Backed Virtual disk preservation inside the sweep), adds a per-driver diagnostic loop to the source-ownership classifier, and admits SCSI to the workspace bus allowlist for the running OS volume only. It does not bump ScriptVersion and does not change the DesiredStateId. The URL-builder fix is inert on a machine whose registered WIM or LKG is usable; the sweep suppression is the main safety-boundary addition; the classifier diagnostic and the SCSI allowlist are the main observability and workspace-eligibility changes.v50 patch 3 hardens the manager config trust gate by replacing the v50 patch 1 owner-only check with Test-PathTrustedForSystem (owner plus effective-DACL mask, split by object class), replaces the v50 patch 1 resume-task protected-path guard with a staging design (the SYSTEM resume task executes a staged copy of the running script at C:\Recovery\OEM\Resume\WinRE.ps1 under an explicit DACL rather than the script’s original path), and closes the correctness gaps identified by independent review: the Restore action preserves the resume task when it cannot confirm WinRE is enabled after a re-enable attempt (only ok counts, not reboot); Remove-StrayRecoveryPartitions positively verifies each deletion with a terminating re-query; Get-GitHubBaseWinRE rejects an empty archive-parts list with a named reason; recovery-volume drive-letter normalization is scoped to the OS disk and fails closed on a provider error; Add-ManagerBackupRoot preserves volume roots (E:\ no longer truncates to E:); and Get-WorkDirCandidates fails closed on a volume-enumeration error. The wrapper and helpers ship additional fixes: Cleanup-Backups.ps1 rejects reparse-point backup directories during discovery and revalidates before deletion; the Restore picker enumerates the manager config catalogue with WIM-only acceptance and a trust-gated config read; argument quoting doubles trailing backslashes in Start-Process paths; and the cleanup helper returns a non-zero exit code when deletions fail. The map builders Build-DellWinPEMap.ps1 and Build-HPWinPEMap.ps1 gain the empty-map refusal Build-LenovoWinPEMap.ps1 has carried since v47 patch 3, and Build-LenovoWinPEMap.ps1 resolves curl-impersonate from the GitHub Releases API’s releases/latest endpoint with a download-host allowlist. It does not bump ScriptVersion and does not change the DesiredStateId. A follow-up revision later in the same cycle added further corrections: the Test-PathTrustedForSystem ACE loop now fails closed on an unresolvable SID rather than silently skipping the ACE (with the same fix mirrored to the duplicated trust helper in Cleanup-Backups.ps1 and to the compressed inline trust check in WinRE-Manager.cmd’s Restore TARGET_COMMAND); Invoke-RestoreAction’s WIM-deployment-failure branch now captures the target WIM’s SHA256 before the deploy attempt and again after the failure, preserving the state file, checkpoint, and deferral marker only when the target can be proven unchanged and invalidating them otherwise; and Cleanup-Backups.ps1’s numeric-selection branch now handles the single-backup case correctly (with exactly one backup present under a root, selecting it by its displayed number now proceeds to confirmation and deletion rather than reporting No matching backups selected.).
else branch when the currently-registered WinRE status could not be classified, so an indeterminate status skipped the disable block and reached deployment without the normal assurance that WinRE was disabled; this now fails closed with $Script:ResumeTaskShouldPersist = $true and $EXIT_FATAL, and is the fifth instance of the fail-closed defect class named in .NOTES since v49 patch 2. Twelve additional full-update exit sites set $Script:ResumeTaskShouldPersist = $true before exiting, raising the persist-site count to eighteen — the invariant is that when the full-update operation has changed recovery state and cannot positively verify an acceptable final recovery route, the resume task must not be unregistered. Remove-StrayRecoveryPartitions now applies the internal-bus allowlist (ATA, SATA, NVMe, RAID, SAS, Spaces, Virtual, File Backed Virtual, SCM) as its disk-scoping gate; non-internal-bus disks (USB, SD/MMC, iSCSI, Fibre Channel, unknown) are preserved individually, matching the workspace selector’s scoping. The Get-PartitionPlan shrink and extend deltas use explicit -gt comparisons on [int64] operands, fixing a Surface Pro 3 field crash where the vulnerable [Math]::Max(0, ...) form threw on a ~4.9 GB extend delta and defeated the self-healing resume task on every subsequent invocation. Test-PathTrustedForSystem skips InheritOnly ACEs (the stock C:\ProgramData ACL false-positive), with the same fix landed in all three copies. Remove-StagingDirectorySafely replaces the recursive staging cleanup with an expected-child-enumeration + individual-delete form that refuses reparse points, subdirectories, unexpected content, and non-directory paths. The staging parent-chain trust check is now warn-only (the C:\Recovery\OEM residual risk is accepted and documented rather than closed), and two script-scope flags ($Script:ResumeStagingTaskInvalid, $Script:ResumeTaskCompromiseUnresolved) force a fatal exit at Main when the staging path cannot be verified and an existing task cannot be positively confirmed as removed. It does not bump ScriptVersion and does not change the DesiredStateId.Because none of these patches changes ScriptVersion or the DesiredStateId, an already-completed machine will not rerun automatically; the deployment mechanism must invoke the script explicitly to pick the fixes up. The next natural rebuild (manifest bump, OEM pack version change, Windows build change, or CPU/VMD presence change) picks them up regardless.
Patch 5 also retains ScriptVersion and the DSI recipe, while adding a separate trusted pending-operation artifact. Its rollback requirements are above; the statement about unchanged ordinary checkpoint/state schemas does not mean an unfinished pending deployment can be ignored.
dism /cleanup-image /StartComponentCleanup /ResetBase invocation from Step 3.base.wim cleanup on the abort branch is retained and does not need rollback.try block and the corresponding release in the finally block.$NetworkTimeoutSeconds to its absence on each call.Ensure-AdequateRecoveryPartition; revert Get-LenovoWinPEPack to a two-state return; revert the VMD presence check to treat enumeration errors as absent; remove the Step 2 stale-file cleanup; restore the earlier OS-fallback remediation wording.Find-SuitableRecoveryPartition and the main-flow $existingRecoveryParts back to accepting label-OR-type; the active-location classifier and the final-verification classifier back to promoting a label-only match to DEDICATED — remove the VMD extraction directory cleanup, and remove the C: encryption-state lookup from the destructive-replacement WARN.WinRE status: ..., Version: ..., Source WIM build: ..., Post-deploy WIM build: ...) from the startup, force-upgrade, and post-deploy paths; remove the Version extraction from Get-WinREState; remove the -ErrorAction SilentlyContinue guard from the two Get-Partition -DiskNumber calls in Get-RecoveryPartitions; revert the four Ensure-AdequateRecoveryPartition hardenings to their pre-v46-patch-2 form.-SourceHash binding and revert the checkpoint validator to its pre-patch-2 $candidateHashes form; remove the Select-BaseWinRESource helper and inline its logic back into Step 2 and the checkpoint validator; revert the conservative null-source-hash handling; restore $ActiveLocationHash as an unconditional participant in checkpoint validation; revert the Win32_ComputerSystemProduct.Version trim; revert the workspace candidate filter to IsSystem alone; remove the drive-letter assignment verification (the DOS Devices registry check, the post-assignment re-query, and the loop’s target-partition / target-disk bail-out); revert Get-GitHubBaseWinRE to throw on extraction failure; revert the extension-failure fallback geometry and sizing to the pre-patch-2 form (including the layout assertion’s use of $plan.AlignedManagedExtentEnd); revert the duplicate Verified partition log line suppression; remove the unrecognized-route guard.Remove-ItemIfExist to log unconditionally; revert the enable-only -not $targetPart branch to $needInject = $false; revert the seven plan-rejection reasons to the unenriched form; revert the race-detector comment to the “microseconds” phrasing.try block; remove the $cachedSourceHash / $cachedSourceBuild / $cachedSourceMetadata capture and revert the state-write section to re-reading $SourceWim; revert the two comment corrections. None of these affect the state-file schema or the DesiredStateId.-ErrorAction SilentlyContinue; the post-deletion partition verification back to querying the specific partition with -ErrorAction SilentlyContinue; the WinRE status determination back to treating an unknown status as the no-disable-step-required case; the storage-controller enumeration back to return @($result)); restore the removed Get-DriverVersionFromInf function; revert the .NOTES never-downgrade wording; remove the two wrapper helper scripts and the three conditionally-visible menu entries; revert the wrapper’s DryRun runner to direct invocation.v50 patch 2: revert the Get-GitHubBaseWinRE URL builder from "Win10/x64" back to "Win10"; remove Test-RunningInVirtualMachine, the sweep suppression early-return at the top of Remove-StrayRecoveryPartitions, and the per-disk File Backed Virtual preservation inside the sweep’s disk loop; revert the classifier’s per-driver diagnostic loop to the v49 count-only form; revert the workspace bus allowlist so SCSI is excluded entirely. None of these affect the state-file schema or the DesiredStateId.
v50 patch 3: revert the shared Test-PathTrustedForSystem helper and the extended manager config trust check to their v50 patch 1 forms; revert the resume-script staging design to the v50 patch 1 protected-path guard; revert the post-deletion verification in Remove-StrayRecoveryPartitions, the empty archive-parts guard in Get-GitHubBaseWinRE, the OS-disk scope and fail-closed provider-error handling on the recovery-volume drive-letter normalization, the volume-root preservation in Add-ManagerBackupRoot, and the fail-closed workspace volume enumeration in Get-WorkDirCandidates; revert the wrapper Restore catalogue enumeration, argument quoting, and cleanup helper changes; revert the Dell and HP empty-map refusals and the Lenovo curl-impersonate resolution. None of these affect the state-file schema or the DesiredStateId.
Main’s full-update path; revert the twelve additional persist-set sites (the enumeration is in .NOTES); revert the internal-bus scoping on Remove-StrayRecoveryPartitions; revert the Get-PartitionPlan size arithmetic back to [Math]::Max(0, ...) (which will re-introduce the Surface Pro 3 Int32 overflow); revert the InheritOnly skip in Test-PathTrustedForSystem and its two mirror copies; revert Remove-StagingDirectorySafely back to Remove-Item -Recurse; revert the warn-only parent-chain check to a hard refusal (or remove it); revert the two lifecycle flags and the Main FATAL exit on compromise. None of these affect the state-file schema or the DesiredStateId.None of these rollbacks affects the state-file schema or the DesiredStateId. (The v47 patch 1 rollback does affect the schema — it introduces the DeployedWinREMetadata field — and is documented separately under “v47 patch 1 migration” above.)
The script’s exit codes carry meaning. See exit-codes.md for the full matrix.
For MDM / orchestration:
| Exit code | Recommended action |
|---|---|
| 0 | None. Record success. |
| 1 | Reboot at the next convenient window, then verify the next run and registration. Pending deployment material must remain until completion is confirmed. |
| 2 | Inspect the log for the specific deferral, preserved-image decision, constrained fallback or recoverable failure. Check current registration, state, deferral marker and pending-deployment record. Warning does not prove recovery is bootable. See exit-codes.md. |
| 3 | Investigate the failed verification, integrity, persistence or enable-failure check. A good active route may remain; preserve any pending record, candidate and resume task. Resolve the reported cause before retrying. See exit-codes.md. |
Do not treat exit code 2 as success. Patch 5 assesses dedicated layout even when DSI and foreign-acceptance hashes match; UsedOSFallback = true no longer makes an OS-hosted image a healthy fast-path outcome. Preserving image bytes does not prohibit relocation.
Do not retry unconditionally. Stable layout, architecture and topology refusals require their stated condition to change. Transient query, network or servicing failures can recover on a later run. Patch 5 reassesses capacity and uses a one-hour backoff for recorded execution failures; an already adequate dedicated route is verified before backoff. Keep unresolved deployment material. See state and idempotency for marker behavior.
Deploy via a Win32 app or a PowerShell script platform script. The Intune “Scripts and remediations” feature is well-suited:
Test-Path C:\ProgramData\OEM\Logs\WinRE-Manager.log and reagentc /info reports Enabled.WinRE.ps1 invoked as SYSTEM.For a curated deployment, package the script as an Intune Win32 app with a detection rule on the log file and reagentc state. Run once, then allow the built-in weekly scheduled task to keep the state fresh.
When using Intune to push a remediation, be aware that the remediation script may run outside the scheduled task’s IgnoreNew gate. As of v44 patch 4, the program lock handles this: if the weekly task happens to be running at the same moment, the remediation exits with EXIT_WARNING (code 2) and the message Another WinRE Manager instance is already running (program lock file is exclusively held). This is not a failure. The remediation will succeed on the next cycle, or you can wait for the scheduled task to complete and re-run the remediation manually.
Do not disable the lock to “fix” the remediation. Before patch 4, the same collision caused an EXIT_FATAL (code 3) with a rename error. Some Intune remediation pipelines treated that as a hard failure and retried aggressively, which could produce a cascade of colliding runs. The lock converts the collision into a clean, self-limiting EXIT_WARNING. If your Intune pipeline retries on any non-zero exit, adjust it to treat code 2 as a soft failure (route to a queue) and code 3 as a hard failure (investigate). See exit-codes.md for the recommended orchestration policy.
v49 note. The wrapper’s install option registers a task named Maintain Windows RE against the stable C:\ProgramData\OEM\WinRE-Manager\WinRE.ps1 copy. If your Intune package ships both the wrapper and a scheduled task, decide which one owns the task registration. Registering both produces two distinct scheduled tasks that contend on the same program lock at C:\ProgramData\OEM\Logs\WinREManager.lock, because the lock path is fixed and not derived from the script’s own path — a run from either task serializes against a run from the other, and the loser exits EXIT_WARNING with Another WinRE Manager instance is already running (program lock file is exclusively held). Two differently-named tasks do not collide on each other’s IgnoreNew policy, since that policy is per-task. The recommended arrangement is: the Intune package ships WinRE.ps1, Test-WinRE.ps1, and the map builders; the wrapper is for interactive use on a single machine, not for the fleet deployment. Fleet deployments use the task XML template above or an Intune-registered task with the operator’s chosen script path.
By default, WinRE Manager fetches the driver manifest, the three OEM maps, and the base WIM repository from the project maintainer’s GitHub account. All five artifacts can be replaced with self-hosted equivalents so your fleet does not depend on those external endpoints.
See self-hosting.md for the trust model, the exact URLs and variables to change, the map-builder scripts, and the air-gapped deployment procedure. The v49 pre-deployment gates read the same artifacts (the manifest’s requiredDevices patterns, the OEM pack’s INFs) — keep them complete for the hardware you deploy to.
The log at C:\ProgramData\OEM\Logs\WinRE-Manager.log is append-only and grows unbounded. Rotate it via your existing log-collection pipeline:
WinRE.ps1 does not write to the Event Log; add a wrapper script that reads the last N lines of the log and writes them as an event after each run.C:\ProgramData\OEM\Logs\WinRE-Manager.log.At ~100 log lines per healthy run, an unmanaged machine generates ~5 MB per year. Rotation is not urgent but is worth having.
v49 note. The v49 source-ownership classification, the never-downgrade check, and the pre-deployment storage-applicability gate each log their decision on the runs where they fire (the applicability gate has never fired in the field; the other two are new in v49). If you collect logs, watch for those lines as the first data point on the new pipeline’s behavior on your hardware.
The script is destructive on the recovery partition and non-destructive on the OS partition, but it does modify the OS partition geometry on the shrink path. Roll out in rings:
Test-WinRE.ps1 first, then WinRE.ps1 -DryRun, then WinRE.ps1. Verify exit code 0. A transient exit code 2 from a concurrent scheduled task that happened to be running is not a failure — see “One instance per machine” above.Patch 5 is a local review candidate. The earlier four-machine prerelease review is supplemented by three successful active-recovery replacements and four fast paths on HP and Lenovo hardware on 2026-10-24. See the dated field evidence. Recorded Hyper-V validation verifies corrected deployment, real post-deletion creation/format failures and retries, forced termination followed by automatic SYSTEM boot-task recovery, an actual WinRE boot with OS-disk access, byte-identical foreign-image relocation, and the native maintenance installer core. Those results apply to the tested GPT guest with encrypted C: and protection off; they do not establish every layout, failure site or BitLocker state.
Verify that an adequate dedicated installation avoids unnecessary work; an inadequate/OS-hosted route is assessed even when DSI matches; copy-only WIM bytes are identical; foreign acceptance never becomes CurrentImageHash; and unresolved candidates/records survive interruption and state-persistence failure. Verify last-resort OS-fallback only after actual creation failure on fully decrypted C:; preflight deferral must preserve the prior route instead. Record a recovery-boot test separately from reagentc enablement and SHA256 verification. The existing post-deletion release gate remains in force.
The v50 patch 4 revision does not bump ScriptVersion and does not change the DesiredStateId. It closes two failure-path defects (the Step 5 fail-closed guard and the twelve additional persist-set exits) and hardens three more areas (internal-bus scoping on the non-OS sweep, Int64-safe plan arithmetic, and the staging lifecycle). The canary is primarily observational.
v50 patch 4. The startup line reads ========== WinRE Manager Started (v50 patch 4) ==========.preserved unsupported-bus: disk <n> (bus=USB) in the sweep’s summary rather than a deletion. This was first exercised in the field on the project’s ASUS desktop test machine (2026-10-19), where the JMicron JMS539 USB disk was preserved as expected. If the canary has no such disk, the observation is that the sweep’s summary shows the usual no stray recovery partitions on non-OS disks line.C:\Recovery\OEM but does not refuse registration. If your canary’s C:\Recovery\OEM is user-owned (as was the case on the ASUS test machine), the log should show Resume-script staging: parent directory 'C:\Recovery\OEM' does not satisfy the SYSTEM trust policy. The resume task will still register; this is a warning, not a refusal. followed by the usual Registered temporary resume task ... and Removed temporary resume task ... lines. The residual is accepted, not closed; see SECURITY.md for the full risk statement.C:\Recovery\OEM\Resume should not exist. If it exists after a clean run, the staging cleanup failed and a WARN line should name the reason.Main and Invoke-PendingWinREDeployment. Current direct refusals report an indeterminate-status reason in the summary Why: field; later checks can log Pending deployment stopped: Current WinRE route cannot be verified before target preparation. or Pending deployment stopped: WinRE status became indeterminate before the route switch. Capture the raw reagentc /info output and full log. These are fail-closed refusals; they do not establish that the earlier recovery route is healthy. See status troubleshooting.WinRE.ps1 only. The Cleanup-Backups.ps1 and WinRE-Manager.cmd copies are byte-verified only; a canary that exercises the wrapper’s Restore picker or the cleanup helper on a machine with the stock C:\ProgramData\OEM ACL is a good non-regression check on the two mirror copies.The v50 patch 1 revision bumps ScriptVersion from 49 to 50 and forces one full-update pass per managed machine, but the pipeline’s decisions on an unchanged machine are the same as they were under v49. The canary is primarily about confirming that the new durable-state hardening behaves as expected:
v50 patch 1. The startup line reads ========== WinRE Manager Started (v50 patch 1) ==========.Ownership migration bridge: using historical CurrentImageHash from stale state file ... and, on the follow-up line, Source-ownership classification: Manager-Owned (or the appropriate class for your source).C:\ProgramData\OEM\ with default ACLs, the log should show Registered temporary resume task 'WinRE Manager - Resume' ... at the start of the run and Removed temporary resume task 'WinRE Manager - Resume' at clean completion.Register-ResumeTask: '<scriptDir>' grants write-capable access to '<principal>' ...) and the repair pipeline should proceed without the self-healing hook.-Action Backup run, C:\ProgramData\OEM\WinRE-Manager\manager.json should exist with the destination root recorded in BackupCatalog.Roots. Confirm the file’s containing directory and its parent are both owned by SYSTEM or Administrators (Get-Acl -Path 'C:\ProgramData\OEM\WinRE-Manager' | Format-List Owner).[8] and [C] entries are unconditional. Open WinRE-Manager.cmd on a machine with no default-location backup; both entries should be visible, and the cleanup screen should report No backup found under the default location and exit cleanly.%TEMP%\WinRE-Manager-remote-version.txt does not exist.The v50 patch 2 revision does not bump ScriptVersion and does not change the DesiredStateId. It fixes the GitHub Windows 10 URL builder for the restructured repository folder, adds a non-OS-disk sweep suppression boundary in Remove-StrayRecoveryPartitions, adds a File Backed Virtual disk protection inside that sweep, adds a per-driver diagnostic loop to the source-ownership classifier, and admits SCSI to the workspace bus allowlist for the running OS volume only. Most of the surface is inert on a physical x64 machine, and the canary is primarily observational.
v50 patch 2. The startup line reads ========== WinRE Manager Started (v50 patch 2) ==========.Test-RunningInVirtualMachine: no known hypervisor signature (Manufacturer='...', Model='...') -> treating as physical at the start of the sweep, followed by the usual Stray-recovery cleanup summary: ... line. On a VM guest the log should instead show Test-RunningInVirtualMachine: signature '<sig>' matched ... followed by Stray-recovery cleanup: skipping the non-OS-disk sweep because a known hypervisor signature was detected. Both are correct on their respective machines.Source-ownership decision: pre-strip third-party inventory: N package(s) line: ` File Backed Virtual protection inside the sweep is inert unless a non-OS VHDX is mounted.SCSI OS-volume admission is inert on a machine whose OS disk is not SCSI. A Hyper-V guest whose OS disk is on a virtual SCSI controller does exercise it.The v50 patch 3 revision does not bump ScriptVersion and does not change the DesiredStateId. It hardens the manager config trust gate, replaces the resume-task protected-path guard with a staging design, closes six correctness gaps in production and six in the wrapper and helpers, extends the empty-map refusal to the Dell and HP map builders, and changes the Lenovo builder’s curl-impersonate resolution to the GitHub Releases API’s releases/latest endpoint with a download-host allowlist. The canary is primarily observational plus a small functional smoke test.
v50 patch 3. The startup line reads ========== WinRE Manager Started (v50 patch 3) ==========.Resume-script staging: staged <src> -> C:\Recovery\OEM\Resume\WinRE.ps1 (SHA256=<hash>) at the start of the run, followed by Registered temporary resume task 'WinRE Manager - Resume' against staged copy .... On clean completion the log shows the task unregistered and the staging directory removed. This is the fix for the v50 patch 1 and v50 patch 3-first-revision false positive that disabled the safety net on every development checkout; the success path should now be visible on any machine, including a dev checkout.C:\ProgramData\OEM\WinRE-Manager\manager.json has the stock ACL (the default on a standard install), the backup action should succeed and the log should show no Test-PathTrustedForSystem: WARN line. The v50 patch 3 extended check accepts the stock C:\ProgramData\OEM ACL; the v50 patch 1 check did too, so this is a non-regression check on the field-verified v50 patch 3 behavior.\Windows presence check against a recovery volume with a drive letter fails for a transient provider reason, the log should show Could not verify whether <letter>: contains \Windows (<error>) - skipping drive-letter removal for this recovery volume (fail closed) and the run should continue without removing the letter. This path is code-inspected only and has not been exercised in the field; a canary that produces it is high-signal.Get-Volume call fails transiently, the log should show Get-WorkDirCandidates: could not enumerate volumes: <error> - no workspace candidates will be offered (fail closed; caller will defer) and the run should defer cleanly with the standard no-eligible-workspace message rather than aborting FATAL. This path is code-inspected only.WinRE-Manager.cmd on a machine with an untrusted manager.json (a file owned by a non-admin principal, or a directory owned by a non-admin principal); the Restore screen should fall back to the default root alone rather than reading the untrusted catalogue. On a machine with a trusted config, the Restore screen should enumerate the catalogue entries with [WIM-ONLY, reduced verification] tags for WIM-only backups. Both paths are code-inspected only.E:\WinRE-Backups\) or a bare volume root (E:\); the argument passing into Start-Process should not produce a \" escape. This path is code-inspected only.Cleanup-Backups.ps1 reparse-point rejection. Plant a directory junction or symlink under the default backup root; the cleanup helper should skip it during discovery with ` Skipping reparse point: Test-PathTrustedForSystem (and its two mirror syncs in Cleanup-Backups.ps1 and the wrapper’s compressed inline trust check), and the Restore-failure hash-comparison state invalidation in Invoke-RestoreAction. The fourth is operator-visible: Cleanup-Backups.ps1 now handles the single-backup numeric-selection case correctly (with exactly one backup present under a root, selecting it by its displayed number now proceeds to confirmation and deletion rather than reporting No matching backups selected.). Confirm the fourth on a canary with a single backup present under a registered root.The v49 patch 2 revision does not bump ScriptVersion and does not change the DesiredStateId. It corrects four fail-open classes in safety checks, removes a dead-code function, corrects a .NOTES wording, ships two new wrapper helper scripts (Check-Update.ps1, Cleanup-Backups.ps1), adds three conditionally-visible wrapper menu entries, and adds a child-process runner for DryRun. The canary is primarily observational:
v49 patch 2. The startup line reads ========== WinRE Manager Started (v49 patch 2) ==========..NOTES wording correction and the dead-code removal are inert.[8] Restore and [C] Cleanup are now shown unconditionally.) The v49 patch 2 wrapper hid both entries when no default-location backup existed; the v50 patch 1 release made them unconditional because the screens themselves report when no backup is present. On a v50 patch 2 install, confirm instead that both entries are visible on a machine with no default-location backup, and that the cleanup screen reports No backup found under the default location and exits cleanly.[U] entry smoke test. The [U] Open releases page entry appears only when Check-Update.ps1 reports an update is available. On a machine already running the latest release, the entry is hidden and the version status line reads Up to date. (Historical note: v49 patch 2’s checker used a %TEMP%\WinRE-Manager-remote-version.txt cache to fake the visible case; v50 patch 1 removed the cache, so there is no longer a local file to fake. To exercise the visible case today, run on a machine whose local version is older than the released version.)-Wait on the elevated launcher. Run a backup (option 1) and confirm the wrapper menu does not re-render until the elevated process exits — the backup completes and its menu entries appear on the same return.The v49 revision bumps ScriptVersion from 48 to 49 and forces one full-update pass per managed machine. The pass is not materially slower than any other full-update pass. The canary is primarily about confirming that the new gates behave as expected on your fleet’s hardware and confirming that the wrapper’s new menu works as documented.
Watch for:
Operating mode: DEDICATED confirms the end state. (A never-downgrade detection does not produce this shape — it discards the candidate and exits 2 before the applicability gate runs.)Foreign-With-Drivers source preservation. The v49 pipeline skipped the strip and injection, dismounted with -Discard, and exited EXIT_WARNING without deploying anything. The existing WinRE route is untouched; the state file records ForeignSourceAcceptedHash so subsequent runs recognize the preserved source and take the fast path. This is the intended v49 behavior for a source the manager did not deploy. If your fleet has machines whose registered WinRE was populated by vendor servicing tools, expect this line; if you want the manager’s recipe applied, the source must be replaced with a Manager-Owned, Manager-Lineage, or Foreign-No-Drivers source.-Discard, the source preserved, the state file records ForeignSourceAcceptedHash, and the run exits 2. The existing WinRE route is untouched. This is the intended v49 behavior for a machine whose source would regress a driver. Watch for repeated detections on the same driver across the fleet — that suggests the manifest or OEM pack is stale for your hardware.EXIT_WARNING, the WIM is not written to the active route, and the old recovery route is intact.WinRE Manager - Resume task after a run. The v49 temporary resume task is preserved on interruption. Do not delete it manually — the next boot or the T+1h one-shot will complete the operation. If the task keeps reappearing after each attempt, the interrupted operation is failing in the same way every time; read the log around the failing step.Wrapper usability canary. On a single machine, run WinRE-Manager.cmd and confirm the reordered menu appears as documented: SAFETY (backup) at the top, DIAGNOSTICS next, MAINTENANCE next, REPAIR next with the yellow LIVE chip on the run-for-real option, RECOVERY last with the restore option visible when a default-location backup exists, and Quit bound to the Q key. Confirm the install / remove maintenance options (5 and 6) register and unregister the Maintain Windows RE task successfully. Confirm the backup (option 1) and restore (option 8) actions complete against a real backup directory.
-Action Backup on a canary and confirm the backup.json sidecar is written alongside the WIM copy. Run a -Action Restore against that backup and confirm the WIM is restored, the state file, checkpoint, and deferral marker are deleted (the WIM changed, so the deployment identity is invalidated), and reagentc /info reports Enabled. The three restore mid-transformation failure paths have not been exercised in the field; if the canary produces any, capture the full log and file a bug — the transactional helper’s rollback behaviour on real storage is high-signal.The v48 patch 2 revision does not bump ScriptVersion and does not change the DesiredStateId. It adds the fail-fast elevation guard, a source-WIM hash cache that closes a pre-existing enable-only fallthrough path, a resize-target resynchronisation fix on the extension-failure fallback path (the D1 fix), and several cosmetic log and comment corrections. The canary is primarily observational:
v48 patch 2. The startup line reads ========== WinRE Manager Started (v48 patch 2) ==========..\scripts\WinRE.ps1 -DryRun should produce a single FATAL log line (FATAL: WinRE Manager requires an elevated (Administrator) PowerShell session.) and exit code 3 in milliseconds. The only file-system operation on the refusal path is the creation of the log directory that the FATAL line is written into. From an elevated prompt, the same command should proceed as in v48 patch 1./setreimage fails. The change is code-review-only in v48 and has not been exercised in the field.The v48 patch 1 revision bumps ScriptVersion from 47 to 48 and forces one full-update pass per managed machine. The pass is not materially slower than any other full-update pass on the ordinary non-intervening path; the intervening-anchor path adds roughly one additional minute of anchor resize on the anchored machine class.
Watch for:
Machines that exit 0 after the first v48 full-update pass. The normal case. The log should show the architecture gate line (Architecture gate passed: x64), the LocalInputsId: <hash> line, and — on a machine whose only candidate recovery partition is undersized and whose predecessor on the OS disk is a shrinkable data partition — the Intervening-anchor plan: anchor is disk N part M; anchor shrink ... line followed by the anchor shrink, delete, New-Partition, layout assertion, and reagentc /enable sequence. Operating mode: DEDICATED confirms the end state.
Machines whose log shows Intervening-anchor plan: ... and complete DEDICATED. This is the v48 feature working on the exact layout that motivated it (the AMD Ryzen 7 5825U machine with C: | D: | Recovery). The 2026-10-06 field run confirmed this path end-to-end; a canary that produces the same shape is expected.
Machines whose log shows Unsupported OS architecture '<arch>' and exit 2. The v48 architecture gate refused. This is expected on ARM64, x86, or machines whose architecture could not be resolved. No state was committed; the machine is unchanged. This is a stable deferral, not a failure: any machine in the fleet whose architecture is not x64 will continue to exit 2 on every run until the manager adds support or the machine is replaced. ARM64 support would be a separate, tested change to the WinRE image pipeline.
Machines whose log shows intervening anchor is N MiB smaller than the plan requires ... and exit 2. The v48 surplus-case rejection. The old recovery partition is intact; no partition was touched. Resolve the layout (extend the anchor to close the gap, or reduce the desired recovery partition size) and delete the state file and deferral marker to force a retry. See troubleshooting.md.
Machines whose log shows recovery-typed partitions exist beyond the intervening anchor's recovery cluster and exit 2. The v48 multi-intervening rejection. This is unchanged behaviour from v47 for the multi-intervening case; the message is now enriched with Format-PartitionRef entries naming the intervening partitions.
Machines whose log shows Preserving existing target ... as rollback copy at <path>. The v48 transactional WIM replacement took the rollback-copy branch, meaning the deployment target was an existing partition with an existing WIM. The subsequent log lines confirm the copy, the hash verification, and the release of the rollback copy after /setreimage and /enable. The branch is expected on the reuse path and on the OS-fallback path; it is skipped on the create-fresh-partition path, where there is no pre-existing WIM to preserve.
Machines whose log shows Deploy-WimTransactional ... copy failed - restoring rollback copy and exits code 3 (EXIT_FATAL). The transactional replacement caught a copy failure. The rollback copy was restored and hash-verified by Deploy-WimTransactional before it returned failure, so the previous WIM is in place on the active route — but both call sites (Deploy-WimToPartition and the OS-fallback deploy branch) treat any $false return as fatal and exit before /setreimage or /enable is attempted. The machine is left with WinRE disabled and the previous WIM in place; the next scheduled run re-attempts deployment. This branch is code-review-only in v48 and has not been exercised in the field. If a canary hits it, capture the full log per the Reporting a bug section.
$needInject = $true forced by the DSI mismatch and will exit 2 with Offline fallback: the machine requires a full update, since a rebuild needs the live manifest. The LocalInputsId comparison does not fire on that path; it fires when a full-update-needing machine has a v48 state file and its hardware has drifted. The next online run writes the v48 state file and the anchor.LocalInputsId mismatch (v48 patch 1). A machine whose state file was written by v48 (with a LocalInputsId), whose next run is offline, and whose locally-observable deployment inputs have changed (hardware identity, OS build, CPU vendor/generation) will exit 2 with Offline fallback: stored LocalInputsId <hash> does not match the current locally-computable inputs <hash>. This is a protective deferral: the stored DesiredStateId no longer describes this machine. The machine is unchanged; bring it online so a fresh manifest can be fetched and a new DSI computed. Note that this check fires before the offline fast path evaluates the drift detector, so a machine with both a LocalInputsId mismatch and a metadata anchor mismatch reports the LocalInputsId line first.The v47 patch 2 revision does not bump ScriptVersion, and on the ordinary machine it does not change the DesiredStateId. Two conditional rebuild triggers apply to a narrow machine class:
A machine with a v47 patch 1 Step 3 checkpoint on disk at the moment of the upgrade has that checkpoint invalidated on its first v47 patch 2 run. Legacy v47 patch 1 Step 3 checkpoints carry no source-content hash, and the new validator requires one; the run rebuilds from Step 2 against the current source. This is the correct convergence for a machine whose checkpoint lineage cannot be proven under the new rules — the alternative (accepting the checkpoint as-is) would leave the exact lineage ambiguity this patch exists to close.
A machine whose Win32_ComputerSystemProduct.Version field is padded with trailing whitespace (observed: ASUS) and whose padded value is at least four characters long while its trimmed value is shorter than four sees a one-time DesiredStateId change from the Version-trim fix. The HW component changes from the four-character prefix of the padded value to <vendor>|<model>|UNKN, because the trimmed value falls below the four-character machine-type length threshold. Those machines rebuild once on the next scheduled run. All other machines continue on the fast path.
Everything else in v47 patch 2 is either a hardening fix on an error path — the OS-fallback missing-WIM guard, the base-WIM copy-integrity check, the workspace candidate filter, the extension-failure fallback geometry and sizing, the unrecognized-route guard, Get-GitHubBaseWinRE’s return contract, the Step 3 source-content-hash binding, and the checkpoint validator’s use of Select-BaseWinRESource — or a comment or log correction. None of these changes the deployed bytes on a healthy machine.
The script does not have an uninstall path. To disable it:
schtasks /Delete /TN "WinRE Manager" /F
schtasks /Delete /TN "WinRE Manager Weekly" /F
The two deletions cover the schtasks.exe two-task form. The XML form above registers a single task named WinRE Manager with both triggers; a deployment that used the XML template needs only the first line. The second line is a no-op on an XML-deployed machine — schtasks /Delete will report the task not found — and is harmless.
If the wrapper’s install option was used, the task name is Maintain Windows RE:
schtasks /Delete /TN "Maintain Windows RE" /F
The wrapper’s removal option (menu option 6 — Remove automatic maintenance) performs the same unregistration.
The state file, deferral marker, log, lock file, and any deployed recovery partition remain. The machine is in a healthy end state and Windows Update will continue to service the recovery image normally. The lock file at C:\ProgramData\OEM\Logs\WinREManager.lock is inert once the scheduled task is removed; it can be deleted manually if desired, and it will be recreated if the script is ever run again. The deferral marker at C:\Recovery\OEM\winre_partition_deferred.json is likewise inert; it can be deleted manually.
If the wrapper’s install option was used, the installed copy at C:\ProgramData\OEM\WinRE-Manager\WinRE.ps1 is left in place after removal. Delete the containing directory manually if you want it gone:
Remove-Item "C:\ProgramData\OEM\WinRE-Manager" -Recurse -Force
If a WinRE Manager - Resume scheduled task is present, it indicates an interrupted Repair or Restore; do not delete it manually unless you intend to abandon the interrupted operation. To remove it after resolving the interrupted state:
schtasks /Delete /TN "WinRE Manager - Resume" /F
If you need to revert a machine to its pre-WinRE-Manager state, restore the partition layout from a backup. The script does not create one.
To revert a DesiredStateId change specifically, see the “Rollback” subsections under “v44 patch 1 migration”, “v45 patch 1 migration”, “v46 patch 1 migration”, “v47 patch 1 migration”, “v48 patch 1 migration”, and “v49 migration” above. To revert code from a patch that does not change the DesiredStateId, see the “Rollback for later non-bumping patches” subsection above.