Files
fogsnippets/02_WindowsUpdates/WindowsUpdates.ps1
Stefan Tollkühn ec74d4a2c1 Initial commit
2025-09-18 14:02:17 +02:00

85 lines
2.7 KiB
PowerShell

Start-Transcript -Path $env:Temp\$(Get-Date -Format "yyyyMMddHHmm")_winupdate_via_fog.log
Write-Host "--- Running Windows Update ---"
Write-Host "Searching for updates..."
$UpdateSession = New-Object -ComObject "Microsoft.Update.Session"
$UpdateSearcher = $UpdateSession.CreateupdateSearcher()
$SearchCriteria = "IsHidden=0 and IsInstalled=0"
$SearchResult = $UpdateSearcher.Search($Criteria)
Write-Host "List of applicable items on the machine:"
If ($SearchResult.Updates.Count -eq 0) {
Write-Host "There are no applicable updates."
} Else {
$DownloadReq = $False
$i = 0
ForEach ($Update in $SearchResult.Updates){
$i++
If ( $Update.IsDownloaded ) {
Write-Host $i">" $Update.Title "(downloaded)"
} Else {
$DownloadReq = $true
Write-Host $i">" $Update.Title "(not downloaded)"
}
}
If ( $DownloadReq ) {
Write-Host "Creating collection of updates to download..."
$UpdatesToDownload = New-Object -ComObject "Microsoft.Update.UpdateColl"
ForEach ($Update in $SearchResult.Updates){
$UpdatesToDownload.Add($Update) | out-null
}
Write-Host "Downloading updates..."
$Downloader = $UpdateSession.CreateUpdateDownloader()
$Downloader.Updates = $UpdatesToDownload
$Downloader.Download()
Write-Host "List of downloaded updates:"
$i = 0
ForEach ($Update in $SearchResult.Updates){
$i++
If ( $Update.IsDownloaded ) {
Write-Host $i">" $Update.Title "(downloaded)"
} Else {
Write-Host $i">" $Update.Title "(not downloaded)"
}
}
} Else {
Write-Host "All updates are already downloaded."
}
$UpdatesToInstall = New-Object -ComObject "Microsoft.Update.UpdateColl"
Write-Host "Creating collection of downloaded updates to install..."
ForEach ($Update in $SearchResult.Updates){
If ( $Update.IsDownloaded ) {
$UpdatesToInstall.Add($Update) | out-null
}
}
If ( $UpdatesToInstall.Count -eq 0 ) {
Write-Host "Not ready for installation."
} Else {
Write-Host "Installing" $UpdatesToInstall.Count "updates..."
$Installer = $UpdateSession.CreateUpdateInstaller()
$Installer.Updates = $UpdatesToInstall
$InstallationResult = $Installer.Install()
If ( $InstallationResult.ResultCode -eq 2 ) {
Write-Host "All updates installed successfully."
} Else {
Write-Host "Some updates could not installed."
}
If ( $InstallationResult.RebootRequired ) {
Write-Host "One or more updates are requiring reboot."
#Write-Host "Reboot system now !!"
#shutdown.exe /r /t 0
# Write-Host "Shutdown system now !!"
# shutdown.exe /s /t 0
} Else {
Write-Host "Finished. Reboot are not required."
}
}
}
Stop-Transcript