Worklet: Force Check\Install Windows Updates

  • 13 March 2024
  • 1 reply
  • 27 views

Badge

Evaluation Code:

# Check for pending updates
$updateSession = New-Object -ComObject Microsoft.Update.Session
$updateSearcher = $updateSession.CreateUpdateSearcher()
$updates = $updateSearcher.Search("IsInstalled=0")

# If there are pending updates, proceed
if ($updates.Updates.Count -gt 0) {
Write-Host "There are pending updates. Proceeding..."
exit 1
}
else {
Write-Host "No pending updates. Exiting..."
exit 0
}

Remediation Code:

# Check for administrative privileges
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Write-Host "Please run this script as an administrator."
exit
}

# Save the current execution policy
$originalPolicy = Get-ExecutionPolicy

# Set the execution policy to allow scripts
Set-ExecutionPolicy Bypass -Scope Process -Force

# Install NuGet
Install-PackageProvider -Name NuGet -Force
Get-PackageProvider -Name NuGet
Register-PackageSource -Name NuGet.org -Location https://www.nuget.org/api/v2 -ProviderName NuGet -Trusted -Force

# Install PSWindowsUpdate
Install-Module -name PSWindowsUpdate -force

# Install Windows updates
Write-Host "Checking for updates..."
$updates = Get-WindowsUpdate -MicrosoftUpdate
if ($updates.Count -eq 0) {
Write-Host "No updates found."
} else {
Write-Host "Found $($updates.Count) update(s). Installing updates..."
Install-WindowsUpdate -AcceptAll
Write-Host "Updates installed successfully."
}

# After script execution, revert to the original execution policy
Set-ExecutionPolicy $originalPolicy -Scope Process -Force

This Worklet allows you to check for windows updates and install them and then follows up with the results in the activity log. Utilizes PSWindowsUpdate.


1 reply

Userlevel 5
Badge

Thank you for sharing this!! 

Reply