Publish Windows patch agent bootstrap scripts
This commit is contained in:
@@ -0,0 +1,248 @@
|
||||
Set-StrictMode -Version Latest
|
||||
|
||||
function Get-WpmPendingReboot {
|
||||
[CmdletBinding()]
|
||||
param()
|
||||
|
||||
$checks = [ordered]@{
|
||||
ComponentBasedServicing = Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending'
|
||||
WindowsUpdate = Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired'
|
||||
PendingFileRename = $false
|
||||
ComputerRename = $false
|
||||
}
|
||||
|
||||
try {
|
||||
$sessionManager = Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager' -Name PendingFileRenameOperations -ErrorAction SilentlyContinue
|
||||
$checks.PendingFileRename = [bool]$sessionManager.PendingFileRenameOperations
|
||||
}
|
||||
catch {
|
||||
$checks.PendingFileRename = $false
|
||||
}
|
||||
|
||||
try {
|
||||
$activeName = (Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName' -Name ComputerName -ErrorAction Stop).ComputerName
|
||||
$pendingName = (Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName' -Name ComputerName -ErrorAction Stop).ComputerName
|
||||
$checks.ComputerRename = $activeName -ne $pendingName
|
||||
}
|
||||
catch {
|
||||
$checks.ComputerRename = $false
|
||||
}
|
||||
|
||||
[pscustomobject]@{
|
||||
RebootRequired = @($checks.Values | Where-Object { $_ }).Count -gt 0
|
||||
Reasons = @($checks.GetEnumerator() | Where-Object { $_.Value } | ForEach-Object { $_.Key })
|
||||
Checks = $checks
|
||||
}
|
||||
}
|
||||
|
||||
function Get-WpmWindowsUpdateStatus {
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[switch]$IncludeDrivers,
|
||||
[switch]$IncludeInstalledHistory
|
||||
)
|
||||
|
||||
$pendingReboot = Get-WpmPendingReboot
|
||||
$result = [ordered]@{
|
||||
schemaVersion = '2026-10-05.1'
|
||||
platform = 'windows'
|
||||
hostname = $env:COMPUTERNAME
|
||||
fqdn = $null
|
||||
domain = $null
|
||||
checkTimeUtc = (Get-Date).ToUniversalTime().ToString('o')
|
||||
osCaption = $null
|
||||
osVersion = $null
|
||||
osBuild = $null
|
||||
lastBootUtc = $null
|
||||
pendingUpdates = 0
|
||||
pendingSecurityUpdates = 0
|
||||
pendingUpdatesList = @()
|
||||
rebootRequired = [bool]$pendingReboot.RebootRequired
|
||||
rebootReasons = @($pendingReboot.Reasons)
|
||||
lastPatchSuccess = $null
|
||||
lastPatchFailure = $null
|
||||
lastWindowsUpdateSearchResult = $null
|
||||
lastWindowsUpdateSearchError = $null
|
||||
installedHistory = @()
|
||||
}
|
||||
|
||||
try {
|
||||
$cs = Get-CimInstance -ClassName Win32_ComputerSystem -ErrorAction Stop
|
||||
$os = Get-CimInstance -ClassName Win32_OperatingSystem -ErrorAction Stop
|
||||
$result.fqdn = if ($cs.Domain -and $cs.Domain -ne 'WORKGROUP') { "$($cs.DNSHostName).$($cs.Domain)" } else { $cs.DNSHostName }
|
||||
$result.domain = $cs.Domain
|
||||
$result.osCaption = $os.Caption
|
||||
$result.osVersion = $os.Version
|
||||
$result.osBuild = $os.BuildNumber
|
||||
$lastBoot = if ($os.LastBootUpTime -is [datetime]) { $os.LastBootUpTime } else { [Management.ManagementDateTimeConverter]::ToDateTime($os.LastBootUpTime) }
|
||||
$result.lastBootUtc = $lastBoot.ToUniversalTime().ToString('o')
|
||||
}
|
||||
catch {
|
||||
$result.lastWindowsUpdateSearchError = "CIM inventory failed: $($_.Exception.Message)"
|
||||
}
|
||||
|
||||
try {
|
||||
$session = New-Object -ComObject Microsoft.Update.Session
|
||||
$searcher = $session.CreateUpdateSearcher()
|
||||
$criteria = "IsInstalled=0 and IsHidden=0"
|
||||
if (-not $IncludeDrivers) {
|
||||
$criteria += " and Type='Software'"
|
||||
}
|
||||
$search = $searcher.Search($criteria)
|
||||
$result.lastWindowsUpdateSearchResult = [int]$search.ResultCode
|
||||
|
||||
$updates = @()
|
||||
foreach ($update in @($search.Updates)) {
|
||||
$kb = @()
|
||||
try { $kb = @($update.KBArticleIDs) } catch { $kb = @() }
|
||||
$categories = @()
|
||||
try { foreach ($cat in @($update.Categories)) { $categories += $cat.Name } } catch { $categories = @() }
|
||||
$isSecurity = @($categories | Where-Object { $_ -match 'Security' }).Count -gt 0
|
||||
$updates += [pscustomobject]@{
|
||||
title = $update.Title
|
||||
kb = $kb
|
||||
categories = $categories
|
||||
isSecurity = $isSecurity
|
||||
isDownloaded = [bool]$update.IsDownloaded
|
||||
requiresReboot = [bool]$update.RebootRequired
|
||||
severity = $update.MsrcSeverity
|
||||
supportUrl = $update.SupportUrl
|
||||
}
|
||||
}
|
||||
|
||||
$result.pendingUpdatesList = @($updates)
|
||||
$result.pendingUpdates = @($updates).Count
|
||||
$result.pendingSecurityUpdates = @($updates | Where-Object { $_.isSecurity }).Count
|
||||
}
|
||||
catch {
|
||||
$result.lastWindowsUpdateSearchError = $_.Exception.Message
|
||||
}
|
||||
|
||||
if ($IncludeInstalledHistory) {
|
||||
try {
|
||||
$session = New-Object -ComObject Microsoft.Update.Session
|
||||
$searcher = $session.CreateUpdateSearcher()
|
||||
$count = [Math]::Min(25, $searcher.GetTotalHistoryCount())
|
||||
if ($count -gt 0) {
|
||||
$history = $searcher.QueryHistory(0, $count)
|
||||
$result.installedHistory = @($history | ForEach-Object {
|
||||
[pscustomobject]@{
|
||||
dateUtc = ([datetime]$_.Date).ToUniversalTime().ToString('o')
|
||||
title = $_.Title
|
||||
resultCode = [int]$_.ResultCode
|
||||
hResult = $_.HResult
|
||||
operation = [int]$_.Operation
|
||||
}
|
||||
})
|
||||
$lastSuccess = @($result.installedHistory | Where-Object { $_.resultCode -eq 2 } | Select-Object -First 1)
|
||||
$lastFailure = @($result.installedHistory | Where-Object { $_.resultCode -in @(4,5) } | Select-Object -First 1)
|
||||
if ($lastSuccess) { $result.lastPatchSuccess = $lastSuccess[0].dateUtc }
|
||||
if ($lastFailure) { $result.lastPatchFailure = "$($lastFailure[0].dateUtc) $($lastFailure[0].title) HResult=$($lastFailure[0].hResult)" }
|
||||
}
|
||||
}
|
||||
catch {
|
||||
if ($result.lastWindowsUpdateSearchError) {
|
||||
$result.lastWindowsUpdateSearchError += "; history failed: $($_.Exception.Message)"
|
||||
}
|
||||
else {
|
||||
$result.lastWindowsUpdateSearchError = "history failed: $($_.Exception.Message)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[pscustomobject]$result
|
||||
}
|
||||
|
||||
function Test-WpmPatchWindow {
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$WindowName,
|
||||
[datetime]$Now = (Get-Date),
|
||||
[int]$WindowMinutes = 60
|
||||
)
|
||||
|
||||
$name = $WindowName.Trim().ToLowerInvariant()
|
||||
if ($name -in @('manual/test','manual','test')) {
|
||||
return [pscustomobject]@{ IsOpen = $false; Reason = 'manual window never auto-opens'; WindowName = $WindowName; Now = $Now }
|
||||
}
|
||||
|
||||
$targetDay = switch -Regex ($name) {
|
||||
'wednesday' { [DayOfWeek]::Wednesday; break }
|
||||
'thursday' { [DayOfWeek]::Thursday; break }
|
||||
'friday' { [DayOfWeek]::Friday; break }
|
||||
default { $null }
|
||||
}
|
||||
if ($null -eq $targetDay) {
|
||||
return [pscustomobject]@{ IsOpen = $false; Reason = 'unknown window'; WindowName = $WindowName; Now = $Now }
|
||||
}
|
||||
|
||||
$isOpen = $Now.DayOfWeek -eq $targetDay -and $Now.Hour -eq 2 -and $Now.Minute -lt $WindowMinutes
|
||||
[pscustomobject]@{
|
||||
IsOpen = [bool]$isOpen
|
||||
Reason = if ($isOpen) { 'inside selected 2 AM window' } else { 'outside selected 2 AM window' }
|
||||
WindowName = $WindowName
|
||||
Now = $Now
|
||||
}
|
||||
}
|
||||
|
||||
function Send-WpmPatchStatus {
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory)][object]$Status,
|
||||
[Parameter(Mandatory)][string]$ApiUrl,
|
||||
[string]$ApiToken
|
||||
)
|
||||
|
||||
$headers = @{}
|
||||
if ($ApiToken) { $headers['Authorization'] = "Bearer $ApiToken" }
|
||||
$json = $Status | ConvertTo-Json -Depth 12
|
||||
Invoke-RestMethod -Uri $ApiUrl -Method Post -ContentType 'application/json' -Headers $headers -Body $json
|
||||
}
|
||||
|
||||
function Invoke-WpmWindowsUpdateInstall {
|
||||
[CmdletBinding(SupportsShouldProcess)]
|
||||
param(
|
||||
[switch]$IncludeDrivers,
|
||||
[switch]$AcceptAll,
|
||||
[switch]$IgnoreReboot
|
||||
)
|
||||
|
||||
$session = New-Object -ComObject Microsoft.Update.Session
|
||||
$searcher = $session.CreateUpdateSearcher()
|
||||
$criteria = "IsInstalled=0 and IsHidden=0"
|
||||
if (-not $IncludeDrivers) { $criteria += " and Type='Software'" }
|
||||
$search = $searcher.Search($criteria)
|
||||
|
||||
$updates = New-Object -ComObject Microsoft.Update.UpdateColl
|
||||
foreach ($update in @($search.Updates)) {
|
||||
if (-not $AcceptAll -and $update.EulaAccepted -eq $false) {
|
||||
$update.AcceptEula()
|
||||
}
|
||||
[void]$updates.Add($update)
|
||||
}
|
||||
|
||||
if ($updates.Count -eq 0) {
|
||||
return [pscustomobject]@{ installed = 0; rebootRequired = (Get-WpmPendingReboot).RebootRequired; resultCode = $null; hResult = $null; message = 'No applicable updates.' }
|
||||
}
|
||||
|
||||
if ($PSCmdlet.ShouldProcess($env:COMPUTERNAME, "Install $($updates.Count) Windows updates")) {
|
||||
$downloader = $session.CreateUpdateDownloader()
|
||||
$downloader.Updates = $updates
|
||||
$downloadResult = $downloader.Download()
|
||||
|
||||
$installer = $session.CreateUpdateInstaller()
|
||||
$installer.Updates = $updates
|
||||
$installResult = $installer.Install()
|
||||
|
||||
return [pscustomobject]@{
|
||||
installed = [int]$updates.Count
|
||||
downloadResultCode = [int]$downloadResult.ResultCode
|
||||
resultCode = [int]$installResult.ResultCode
|
||||
hResult = $installResult.HResult
|
||||
rebootRequired = [bool]($installResult.RebootRequired -or (Get-WpmPendingReboot).RebootRequired)
|
||||
message = 'Windows Update install attempted.'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Export-ModuleMember -Function Get-WpmPendingReboot, Get-WpmWindowsUpdateStatus, Test-WpmPatchWindow, Send-WpmPatchStatus, Invoke-WpmWindowsUpdateInstall
|
||||
@@ -0,0 +1,46 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$InventoryApiUrl,
|
||||
[string]$InventoryApiToken,
|
||||
[string]$OutFile = "$env:ProgramData\WheelzPatch\status.json",
|
||||
[switch]$IncludeDrivers,
|
||||
[switch]$IncludeInstalledHistory
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$modulePath = Join-Path $repoRoot 'Modules\WindowsPatchManagement\WindowsPatchManagement.psm1'
|
||||
if (-not (Test-Path $modulePath)) {
|
||||
$modulePath = Join-Path $PSScriptRoot '..\Modules\WindowsPatchManagement\WindowsPatchManagement.psm1'
|
||||
}
|
||||
Import-Module $modulePath -Force
|
||||
|
||||
$status = Get-WpmWindowsUpdateStatus -IncludeDrivers:$IncludeDrivers -IncludeInstalledHistory:$IncludeInstalledHistory
|
||||
|
||||
$inventoryPatch = [pscustomobject]@{
|
||||
source = 'wheelz-windows-patch-agent'
|
||||
hostname = $status.hostname
|
||||
fqdn = $status.fqdn
|
||||
platform = $status.platform
|
||||
patchSource = 'custom-powershell-psu'
|
||||
patchStatus = if ($status.lastWindowsUpdateSearchError) { 'attention' } elseif ($status.pendingUpdates -gt 0) { 'pending' } elseif ($status.rebootRequired) { 'reboot_required' } else { 'healthy' }
|
||||
lastPatchCheck = $status.checkTimeUtc
|
||||
lastPatchSuccess = $status.lastPatchSuccess
|
||||
lastPatchFailure = $status.lastPatchFailure
|
||||
rebootRequired = $status.rebootRequired
|
||||
pendingUpdates = $status.pendingUpdates
|
||||
pendingSecurityUpdates = $status.pendingSecurityUpdates
|
||||
postPatchChecks = 'windows update scan; pending reboot registry checks; last boot timestamp'
|
||||
patchNotes = $status.lastWindowsUpdateSearchError
|
||||
raw = $status
|
||||
}
|
||||
|
||||
$dir = Split-Path -Parent $OutFile
|
||||
if ($dir -and -not (Test-Path $dir)) { New-Item -Path $dir -ItemType Directory -Force | Out-Null }
|
||||
$inventoryPatch | ConvertTo-Json -Depth 16 | Set-Content -Path $OutFile -Encoding UTF8
|
||||
|
||||
if ($InventoryApiUrl) {
|
||||
Send-WpmPatchStatus -Status $inventoryPatch -ApiUrl $InventoryApiUrl -ApiToken $InventoryApiToken | Out-Null
|
||||
}
|
||||
|
||||
$inventoryPatch | ConvertTo-Json -Depth 16
|
||||
@@ -0,0 +1,65 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$RepositoryRawBase = 'https://gitea.wheelytho.com/Wheelz/Docker-Install/raw/branch/main',
|
||||
[string]$InstallRoot = "$env:ProgramData\WheelzPatch",
|
||||
[string]$InventoryApiUrl,
|
||||
[string]$InventoryApiToken,
|
||||
[string]$StatusSchedule = 'Every 4 hours',
|
||||
[string]$PatchSchedule = 'Wednesday after Patch Tuesday · 2:00 AM CT',
|
||||
[switch]$EnablePatchTask,
|
||||
[switch]$Force
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
|
||||
throw 'Run this installer from an elevated PowerShell session.'
|
||||
}
|
||||
|
||||
$moduleDir = Join-Path $InstallRoot 'Modules\WindowsPatchManagement'
|
||||
$scriptsDir = Join-Path $InstallRoot 'WindowsPatchScripts'
|
||||
New-Item -Path $moduleDir,$scriptsDir -ItemType Directory -Force | Out-Null
|
||||
|
||||
$downloads = @(
|
||||
@{ Url = "$RepositoryRawBase/Modules/WindowsPatchManagement/WindowsPatchManagement.psm1"; Path = (Join-Path $moduleDir 'WindowsPatchManagement.psm1') },
|
||||
@{ Url = "$RepositoryRawBase/WindowsPatchScripts/Get-WindowsPatchStatus.ps1"; Path = (Join-Path $scriptsDir 'Get-WindowsPatchStatus.ps1') },
|
||||
@{ Url = "$RepositoryRawBase/WindowsPatchScripts/Invoke-WindowsPatchInstall.ps1"; Path = (Join-Path $scriptsDir 'Invoke-WindowsPatchInstall.ps1') },
|
||||
@{ Url = "$RepositoryRawBase/WindowsPatchScripts/Invoke-WindowsPatchReboot.ps1"; Path = (Join-Path $scriptsDir 'Invoke-WindowsPatchReboot.ps1') }
|
||||
)
|
||||
|
||||
foreach ($item in $downloads) {
|
||||
Invoke-WebRequest -Uri $item.Url -OutFile $item.Path -UseBasicParsing
|
||||
}
|
||||
|
||||
$config = [ordered]@{
|
||||
inventoryApiUrl = $InventoryApiUrl
|
||||
inventoryApiToken = $InventoryApiToken
|
||||
patchWindow = $PatchSchedule
|
||||
rebootPolicyEnabled = $false
|
||||
installedAtUtc = (Get-Date).ToUniversalTime().ToString('o')
|
||||
}
|
||||
$configPath = Join-Path $InstallRoot 'config.json'
|
||||
$config | ConvertTo-Json -Depth 8 | Set-Content -Path $configPath -Encoding UTF8
|
||||
|
||||
$statusArgs = @('-NoProfile','-ExecutionPolicy','Bypass','-File',"$scriptsDir\Get-WindowsPatchStatus.ps1")
|
||||
if ($InventoryApiUrl) { $statusArgs += @('-InventoryApiUrl',$InventoryApiUrl) }
|
||||
if ($InventoryApiToken) { $statusArgs += @('-InventoryApiToken',$InventoryApiToken) }
|
||||
$statusArgument = (($statusArgs | ForEach-Object { if ($_ -match '\s') { '"{0}"' -f $_ } else { $_ } }) -join ' ')
|
||||
$statusAction = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument $statusArgument
|
||||
$statusTrigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(5) -RepetitionInterval (New-TimeSpan -Hours 4) -RepetitionDuration (New-TimeSpan -Days 3650)
|
||||
$statusPrincipal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -RunLevel Highest
|
||||
Register-ScheduledTask -TaskName 'Wheelz Windows Patch Status' -Action $statusAction -Trigger $statusTrigger -Principal $statusPrincipal -Force | Out-Null
|
||||
|
||||
if ($EnablePatchTask) {
|
||||
$patchArgs = @('-NoProfile','-ExecutionPolicy','Bypass','-File',"$scriptsDir\Invoke-WindowsPatchInstall.ps1",'-Force')
|
||||
if ($InventoryApiUrl) { $patchArgs += @('-InventoryApiUrl',$InventoryApiUrl) }
|
||||
if ($InventoryApiToken) { $patchArgs += @('-InventoryApiToken',$InventoryApiToken) }
|
||||
$patchArgument = (($patchArgs | ForEach-Object { if ($_ -match '\s') { '"{0}"' -f $_ } else { $_ } }) -join ' ')
|
||||
$patchAction = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument $patchArgument
|
||||
$patchTrigger = New-ScheduledTaskTrigger -Weekly -WeeksInterval 1 -DaysOfWeek Wednesday -At 2am
|
||||
Register-ScheduledTask -TaskName 'Wheelz Windows Patch Install' -Action $patchAction -Trigger $patchTrigger -Principal $statusPrincipal -Force | Out-Null
|
||||
}
|
||||
|
||||
& "$scriptsDir\Get-WindowsPatchStatus.ps1" -InventoryApiUrl $InventoryApiUrl -InventoryApiToken $InventoryApiToken | Out-Host
|
||||
Write-Host "Wheelz Windows Patch agent installed at $InstallRoot"
|
||||
Write-Host 'Status task: Wheelz Windows Patch Status'
|
||||
if ($EnablePatchTask) { Write-Host 'Patch task: Wheelz Windows Patch Install' } else { Write-Host 'Patch task not enabled yet; rerun with -EnablePatchTask after status reporting is trusted.' }
|
||||
@@ -0,0 +1,69 @@
|
||||
[CmdletBinding(SupportsShouldProcess)]
|
||||
param(
|
||||
[string]$InventoryApiUrl,
|
||||
[string]$InventoryApiToken,
|
||||
[string]$OutFile = "$env:ProgramData\WheelzPatch\last-run.json",
|
||||
[switch]$IncludeDrivers,
|
||||
[switch]$Force,
|
||||
[switch]$IgnoreReboot
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$modulePath = Join-Path $repoRoot 'Modules\WindowsPatchManagement\WindowsPatchManagement.psm1'
|
||||
Import-Module $modulePath -Force
|
||||
|
||||
$before = Get-WpmWindowsUpdateStatus -IncludeDrivers:$IncludeDrivers -IncludeInstalledHistory
|
||||
$run = [ordered]@{
|
||||
source = 'wheelz-windows-patch-agent'
|
||||
hostname = $env:COMPUTERNAME
|
||||
startTimeUtc = (Get-Date).ToUniversalTime().ToString('o')
|
||||
before = $before
|
||||
install = $null
|
||||
after = $null
|
||||
status = 'started'
|
||||
error = $null
|
||||
}
|
||||
|
||||
try {
|
||||
if ($Force -or $PSCmdlet.ShouldProcess($env:COMPUTERNAME, 'Install pending Windows updates')) {
|
||||
$install = Invoke-WpmWindowsUpdateInstall -IncludeDrivers:$IncludeDrivers -IgnoreReboot:$IgnoreReboot -Confirm:$false
|
||||
$run.install = $install
|
||||
Start-Sleep -Seconds 5
|
||||
$run.after = Get-WpmWindowsUpdateStatus -IncludeDrivers:$IncludeDrivers -IncludeInstalledHistory
|
||||
$run.status = if ($install.hResult -and $install.hResult -ne 0) { 'attention' } elseif ($run.after.lastWindowsUpdateSearchError) { 'attention' } elseif ($run.after.pendingUpdates -eq 0) { 'success' } else { 'pending_reboot_or_remaining_updates' }
|
||||
}
|
||||
else {
|
||||
$run.status = 'skipped'
|
||||
}
|
||||
}
|
||||
catch {
|
||||
$run.status = 'failed'
|
||||
$run.error = $_.Exception.Message
|
||||
}
|
||||
finally {
|
||||
$run.endTimeUtc = (Get-Date).ToUniversalTime().ToString('o')
|
||||
$dir = Split-Path -Parent $OutFile
|
||||
if ($dir -and -not (Test-Path $dir)) { New-Item -Path $dir -ItemType Directory -Force | Out-Null }
|
||||
[pscustomobject]$run | ConvertTo-Json -Depth 18 | Set-Content -Path $OutFile -Encoding UTF8
|
||||
|
||||
if ($InventoryApiUrl) {
|
||||
$payload = [pscustomobject]@{
|
||||
source = 'wheelz-windows-patch-agent'
|
||||
hostname = $env:COMPUTERNAME
|
||||
platform = 'windows'
|
||||
patchSource = 'custom-powershell-psu'
|
||||
patchStatus = $run.status
|
||||
lastPatchCheck = $run.endTimeUtc
|
||||
lastPatchSuccess = if ($run.status -in @('success','pending_reboot_or_remaining_updates')) { $run.endTimeUtc } else { $null }
|
||||
lastPatchFailure = if ($run.status -eq 'failed') { "$($run.endTimeUtc) $($run.error)" } else { $null }
|
||||
rebootRequired = if ($run.after) { $run.after.rebootRequired } else { $before.rebootRequired }
|
||||
pendingUpdates = if ($run.after) { $run.after.pendingUpdates } else { $before.pendingUpdates }
|
||||
raw = [pscustomobject]$run
|
||||
}
|
||||
Send-WpmPatchStatus -Status $payload -ApiUrl $InventoryApiUrl -ApiToken $InventoryApiToken | Out-Null
|
||||
}
|
||||
}
|
||||
|
||||
[pscustomobject]$run | ConvertTo-Json -Depth 18
|
||||
if ($run.status -eq 'failed') { exit 1 }
|
||||
@@ -0,0 +1,23 @@
|
||||
[CmdletBinding(SupportsShouldProcess)]
|
||||
param(
|
||||
[string]$Reason = 'Inventory patch orchestration requested reboot',
|
||||
[switch]$Force
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$payload = [ordered]@{
|
||||
source = 'wheelz-windows-patch-agent'
|
||||
hostname = $env:COMPUTERNAME
|
||||
action = 'reboot'
|
||||
reason = $Reason
|
||||
requestedAtUtc = (Get-Date).ToUniversalTime().ToString('o')
|
||||
}
|
||||
|
||||
$outFile = "$env:ProgramData\WheelzPatch\last-reboot-request.json"
|
||||
$dir = Split-Path -Parent $outFile
|
||||
if ($dir -and -not (Test-Path $dir)) { New-Item -Path $dir -ItemType Directory -Force | Out-Null }
|
||||
[pscustomobject]$payload | ConvertTo-Json -Depth 8 | Set-Content -Path $outFile -Encoding UTF8
|
||||
|
||||
if ($Force -or $PSCmdlet.ShouldProcess($env:COMPUTERNAME, $Reason)) {
|
||||
shutdown.exe /r /t 60 /c $Reason /d p:2:17
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
# Windows patching MVP
|
||||
|
||||
Purpose: replace PatchMon for Windows patch execution with a small PowerShell/PowerShell Universal path that feeds the same Inventory patch fields and can later be targeted by the reboot orchestrator.
|
||||
|
||||
## Role split
|
||||
|
||||
PatchMon remains the Linux/Proxmox patch source of truth.
|
||||
|
||||
Windows uses this repo:
|
||||
|
||||
- `Modules/WindowsPatchManagement/WindowsPatchManagement.psm1` for reusable Windows Update, reboot-required, status-posting, and install functions.
|
||||
- `WindowsPatchScripts/Get-WindowsPatchStatus.ps1` for read-only Windows Update status collection.
|
||||
- `WindowsPatchScripts/Invoke-WindowsPatchInstall.ps1` for controlled update installation.
|
||||
- `WindowsPatchScripts/Invoke-WindowsPatchReboot.ps1` for orchestrator-triggered Windows reboot execution.
|
||||
- `.universal/endpoints.ps1` for PSU JSON status ingest/list endpoints.
|
||||
|
||||
Inventory remains the human-facing dashboard/control surface.
|
||||
|
||||
## Normalized Inventory fields
|
||||
|
||||
The collector emits fields designed to map directly to Inventory:
|
||||
|
||||
- `patchSource`: `custom-powershell-psu`
|
||||
- `patchStatus`: `healthy`, `pending`, `reboot_required`, or `attention`
|
||||
- `lastPatchCheck`
|
||||
- `lastPatchSuccess`
|
||||
- `lastPatchFailure`
|
||||
- `rebootRequired`
|
||||
- `pendingUpdates`
|
||||
- `pendingSecurityUpdates`
|
||||
- `postPatchChecks`
|
||||
- `patchNotes`
|
||||
|
||||
Raw Windows Update details are preserved under `raw` so Inventory can start simple and gain richer display later.
|
||||
|
||||
## MVP install on a Windows test host
|
||||
|
||||
Run from elevated PowerShell:
|
||||
|
||||
```powershell
|
||||
$u = 'https://gitea.wheelytho.com/obin/PowerShell-Universal-Help-Desk-Portal/raw/branch/main/WindowsPatchScripts/Install-WindowsPatchAgent.ps1'
|
||||
$s = "$env:TEMP\Install-WindowsPatchAgent.ps1"
|
||||
Invoke-WebRequest -Uri $u -OutFile $s -UseBasicParsing
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $s
|
||||
```
|
||||
|
||||
This installs the scripts under:
|
||||
|
||||
```text
|
||||
C:\ProgramData\WheelzPatch
|
||||
```
|
||||
|
||||
It creates a scheduled task:
|
||||
|
||||
```text
|
||||
Wheelz Windows Patch Status
|
||||
```
|
||||
|
||||
That task runs as SYSTEM every four hours and writes:
|
||||
|
||||
```text
|
||||
C:\ProgramData\WheelzPatch\status.json
|
||||
```
|
||||
|
||||
## PSU status ingest
|
||||
|
||||
If the PSU endpoint is deployed, install the agent with an API target:
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $s -InventoryApiUrl 'https://psu.wheelz.lab/api/wheelz/patch/windows/status'
|
||||
```
|
||||
|
||||
If a bearer token is added later:
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File $s -InventoryApiUrl 'https://psu.wheelz.lab/api/wheelz/patch/windows/status' -InventoryApiToken '<token>'
|
||||
```
|
||||
|
||||
Do not commit API tokens to Gitea.
|
||||
|
||||
## Automatic patch execution
|
||||
|
||||
Do not enable automatic Windows patching until WAC status collection has checked in cleanly and Inventory displays it correctly.
|
||||
|
||||
When ready for a controlled test host:
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File C:\ProgramData\WheelzPatch\WindowsPatchScripts\Invoke-WindowsPatchInstall.ps1 -Force
|
||||
```
|
||||
|
||||
The install script records before/after status in:
|
||||
|
||||
```text
|
||||
C:\ProgramData\WheelzPatch\last-run.json
|
||||
```
|
||||
|
||||
The installer also supports `-EnablePatchTask`, which creates a weekly Wednesday 2:00 AM task. Treat that as a first draft only; final scheduling should come from Inventory policy/PSU/orchestrator rather than hardcoded local schedules.
|
||||
|
||||
## Reboot orchestrator path
|
||||
|
||||
Windows machines should look like Linux machines to Inventory and the reboot orchestrator as much as possible:
|
||||
|
||||
1. Windows collector reports `rebootRequired=true`.
|
||||
2. Inventory stores the same policy fields already used for Linux: `scheduledRebootsEnabled`, `rebootWindow`, and one-time reboot requests.
|
||||
3. Reboot orchestrator sees the Windows target and dispatches to a Windows executor instead of the Linux/Proxmox executor.
|
||||
4. The Windows executor can use PSU, WinRM/OpenSSH, or a local scheduled task trigger to run:
|
||||
|
||||
```powershell
|
||||
C:\ProgramData\WheelzPatch\WindowsPatchScripts\Invoke-WindowsPatchReboot.ps1 -Force
|
||||
```
|
||||
|
||||
5. After reboot, the normal status task checks in again and clears/updates `rebootRequired`.
|
||||
|
||||
## Safety rules
|
||||
|
||||
- Visibility first; automatic install second; automatic reboot last.
|
||||
- Unknown/stale/offline Windows hosts must show as attention/stale, not healthy.
|
||||
- Patch install success and post-reboot/service health are separate states.
|
||||
- Do not install drivers by default.
|
||||
- Do not include feature upgrades in the first MVP.
|
||||
- Do not store secrets in this repo, Obsidian, or Inventory JSON.
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"schemaVersion": "2026-10-05.1",
|
||||
"purpose": "Draft contract so the existing PatchMon Reboot Orchestrator can target Windows machines with the same policy model as Linux.",
|
||||
"inventoryPolicyFields": {
|
||||
"scheduledRebootsEnabled": true,
|
||||
"rebootWindow": "Wednesday after Patch Tuesday · 2:00 AM CT",
|
||||
"rebootTodayOvernightRequested": null,
|
||||
"patchTier": "standard",
|
||||
"patchSource": "custom-powershell-psu"
|
||||
},
|
||||
"windowsStatusFields": {
|
||||
"hostname": "WHEELZWAC",
|
||||
"platform": "windows",
|
||||
"patchStatus": "pending|healthy|attention|reboot_required|stale",
|
||||
"lastPatchCheck": "UTC ISO timestamp",
|
||||
"rebootRequired": true,
|
||||
"pendingUpdates": 0,
|
||||
"pendingSecurityUpdates": 0
|
||||
},
|
||||
"executorOptions": [
|
||||
{
|
||||
"name": "psu-endpoint",
|
||||
"description": "Reboot orchestrator calls a PSU endpoint/job that runs Invoke-WindowsPatchReboot.ps1 on the target. Best fit once PSU remoting/credentials are configured."
|
||||
},
|
||||
{
|
||||
"name": "openssh",
|
||||
"description": "Reboot orchestrator SSHes to Windows OpenSSH and runs powershell.exe -File C:\\ProgramData\\WheelzPatch\\WindowsPatchScripts\\Invoke-WindowsPatchReboot.ps1 -Force."
|
||||
},
|
||||
{
|
||||
"name": "winrm",
|
||||
"description": "Reboot orchestrator uses PowerShell remoting/WinRM to invoke the same local reboot script."
|
||||
}
|
||||
],
|
||||
"requiredGates": [
|
||||
"scheduledRebootsEnabled is true",
|
||||
"selected rebootWindow is open",
|
||||
"Windows status is not stale",
|
||||
"rebootRequired is true",
|
||||
"host is explicitly allowlisted",
|
||||
"executor path is configured and tested"
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user