Something I was playing with to ensure my system updates every day, so I run this at the end of the day…
'Restart-PC.ps1'
# Define log file for capturing the output
$logFile = "c:\windows\temp\windows11update-log.txt"
function Write-Log {
param (
[string]$message
)
$timestamp = (Get-Date).ToString("yyyy-MM-dd HH:mm:ss")
"$timestamp - $message" | Out-File -Append -FilePath $logFile
}
function Update-PC {
Write-Host "Checking for updates..."
Write-Log "Started checking for updates..."
try {
$session = New-Object -ComObject Microsoft.Update.Session
$searcher = $session.CreateUpdateSearcher()
$search = $searcher.Search("IsInstalled=0")
if ($search.Updates.Count -eq 0) {
Write-Host "No updates available."
Write-Log "No updates available."
return
}
Write-Host "$($search.Updates.Count) updates found. Downloading and installing updates..."
Write-Log "$($search.Updates.Count) updates found."
$downloads = New-Object -ComObject Microsoft.Update.UpdateColl
foreach ($update in $search.Updates) {
$downloads.Add($update)
Write-Host "Preparing to download: $($update.Title)"
Write-Log "Preparing to download: $($update.Title)"
}
# Download updates
$downloader = $session.CreateUpdateDownloader()
$downloader.Updates = $downloads
Write-Host "Downloading updates..."
Write-Log "Downloading updates..."
$downloader.Download()
if ($downloader.Status -ne 0) {
Write-Error "Failed to download updates."
Write-Log "Failed to download updates."
return
}
# Install updates
$installer = $session.CreateUpdateInstaller()
$installer.Updates = $downloads
Write-Host "Installing updates..."
Write-Log "Installing updates..."
$installationResult = $installer.Install()
if ($installationResult.ResultCode -eq 2) { # 2 indicates success
Write-Host "Update installation completed."
Write-Log "Update installation completed."
} else {
Write-Error "Failed to install updates. Result Code: $($installationResult.ResultCode)"
Write-Log "Failed to install updates. Result Code: $($installationResult.ResultCode)"
}
} catch {
Write-Error "An error occurred: $_"
Write-Log "An error occurred: $_"
}
}
# Execute the update function
Update-PC
# Prompt for restart
if ($installationResult.ResultCode -eq 2) { # Only restart if updates were installed successfully
Read-Host "Press Enter to restart the computer for the updates..."
Restart-Computer
} else {
Write-Host "No restart required for patching."
Restart-Computer -confirm
}

