@@ -138,6 +138,29 @@ function ExitWhenRebootRequired($rebootRequired = $false) {
138138 }
139139}
140140
141+ # try to repair the windows update settings to work in non-preview mode.
142+ # see https://github.com/rgl/packer-plugin-windows-update/issues/144
143+ # see https://learn.microsoft.com/en-sg/answers/questions/1791668/powershell-command-outputting-system-comobject-on
144+ function Repair-WindowsUpdate {
145+ $settingsPath = ' C:\ProgramData\Microsoft\Windows\OneSettings\UusSettings.json'
146+ if (! (Test-Path $settingsPath )) {
147+ throw ' the windows update api is in an invalid state. see https://github.com/rgl/packer-plugin-windows-update/issues/144.'
148+ }
149+ $version = (New-Object - ComObject Microsoft.Update.AgentInfo).GetInfo(' ProductVersionString' )
150+ $settings = Get-Content - Raw $settingsPath | ConvertFrom-Json
151+ if ($settings.settings.EXCLUSIONS -notcontains $version ) {
152+ $settings.settings.EXCLUSIONS += $version
153+ Write-Output ' Repairing the windows update settings to work in non-preview mode...'
154+ Copy-Item $settingsPath " $settingsPath .backup.json" - Force
155+ [System.IO.File ]::WriteAllText(
156+ $settingsPath ,
157+ ($settings | ConvertTo-Json - Compress - Depth 100 ),
158+ (New-Object System.Text.UTF8Encoding $false ))
159+ }
160+ Write-Output ' Restarting the machine to retry a new windows update round...'
161+ ExitWithCode 101
162+ }
163+
141164ExitWhenRebootRequired
142165
143166if ($OnlyCheckForRebootRequired ) {
@@ -188,7 +211,8 @@ $rebootRequired = $false
188211for ($i = 0 ; $i -lt $searchResult.Updates.Count ; ++ $i ) {
189212 $update = $searchResult.Updates.Item ($i )
190213
191- # crash when the windows update api returns an invalid update object.
214+ # when the windows update api returns an invalid update object, repair
215+ # windows update and signal a reboot to try again.
192216 # see https://github.com/rgl/packer-plugin-windows-update/issues/144
193217 $expectedProperties = @ (
194218 ' Title'
@@ -201,7 +225,7 @@ for ($i = 0; $i -lt $searchResult.Updates.Count; ++$i) {
201225 | Get-Member $expectedProperties `
202226 | Select-Object - ExpandProperty Name
203227 if (! $properties -or (Compare-Object $expectedProperties $properties )) {
204- throw " the windows update api returned a invalid update object. see https://github.com/rgl/packer-plugin-windows-update/issues/144. "
228+ Repair-WindowsUpdate
205229 }
206230
207231 $updateTitle = $update.Title
0 commit comments