AutomoxAutomox

Worklet: Force Check\Install Windows Updates

KTicer
March 13, 2024 at 7:08 pm UTC
#updates#Windows#Worklets

Evaluation Code:

powershell14 lines
# 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:

powershell33 lines
# 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.

This discussion is archived and closed to replies. Continue it in the Automox Community Slack.

Discuss on Slack

Replies (1)

SophiaAXMarch 14, 2024
#1

Thank you for sharing this!!