|Create the Ultimate Smart PowerShell Update Script with Email Notifications and Error Handling

I wanted to create a smart PowerShell Script for updating our servers that was both ready to be executed manually as well as ready to be added as an automated task.  Additionally, I wanted notifications to be generated whenever the script was run with details about the results, just in case we needed to debug any issues in the future.  This is what I came up with:


⁠# Basic Variables
$HostName = $env:COMPUTERNAME
$HostTime = get-date -Format hh:mm
$HostDate = get-date -format D

# SMTP Variables
$SMTPSender = "sender@member.buzz"
$SMTPRecipient = "recipient@member.buzz"
$SMTPMessage = New-Object System.Net.Mail.mailmessage $SMTPSender, $SMTPRecipient$SMTPMessage.IsBodyHTML = $true
$SMTPMessage.IsBodyHTML = $true
$SMTPMessage.Subject = $HostName + " Update Report"
$SMTPClient = new-Object Net.Mail.SmtpClient("smtpserver.com", 587)
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("SMTPUser", "SMTPPassword" )

# CHECK PENDING RESTART
# If the server already has a pending restart it should be done# before installing additional updates.if ((New-Object -ComObject Microsoft.Update.SystemInfo).RebootRequired){
$SMTPMessage.Body = "$($HostDate)
$($HostTime)
$($HostName) has a pending restart that must be completed before installing new updats."
$SMTPClient.Send($SMTPMessage) Restart-Computer -Force}else{ # SEARCH UPDATES # This will find new updates to install. $UpdateResults = (New-Object -ComObject Microsoft.Update.Searcher).Search("IsInstalled=0 and Type='Software'").Updates # CHECK UPDATE COUNT # If there are no updates and you attempt to call # download, an exception is thrown.
if ($UpdateResults.Count -eq 0)
{
$SMTPMessage.Body = "$($HostDate)
$($HostTime)
$($HostName) has checked for updates but coult not find any." $SMTPClient.Send($SMTPMessage)
}
else
{
# DOWNLOAD UPDATES
# Attempt to download updates, writing progress as it goes.
$UpdateDownloader = (New-Object -ComObject Microsoft.Update.Session).CreateUpdateDownloader()
$UpdateDownloader.Updates = $UpdateResults
write-progress -Activity 'Updating' -Status "Downloading $($UpdateDownloader.Updates.count) updates"
$UpdateDownloader.Download()
# INSTALL UPDATES

# Installs the updates that have been downloaded.
$UpdateInstaller = New-Object -ComObject Microsoft.Update.Installer
$UpdateInstaller.Updates = $UpdateResults
$UpdateResult = $UpdateInstaller.Install()
if ($UpdateResult.rebootRequired)
{
$SMTPMessage.Body = "$($HostDate)
$($HostTime)
$($HostName) has installed all available updates and will now reboot."
$SMTPClient.Send($SMTPMessage)
Restart-Computer -Force
}
else
{
$SMTPMessage.Body = "$($HostDate)
$($HostTime)
$($HostName) has installed all available updates and no reboot is required."
$SMTPClient.Send($SMTPMessage) } }}

If you are okay with less control over how your updates work (and don't need notifications), you can use a pre-existing library using the following script:

⁠Set-ExecutionPolicy RemoteSigned -ForceInstall-PackageProvider -Name NuGet -ForceSet-PSRepository -Name "PSGallery" -InstallationPolicy TrustedInstall-Module PSWindowsUpdateImport-Module PSWindowsUpdateAdd-WUServiceManager -ServiceID 7971f918-a847-4430-9279-4a52d1efe18d -Confirm:$falseGet-WUInstall -AcceptAll -Install -AutoReboot

Finally, if this is an automated task, set your Action to start a program (PowerShell.exe) with the following arguments:

⁠sds

Happy scripting!

Other resources:

Install Updates and Reboot with PowerShell

PSWindowsUpdate

Use PowerShell to Install Windows Update and Restart

Comments

To add a comment, please login or register.

Related

Setup Point-to-Site VPN with Ubiquiti EdgeRouter
Learn how to setup a VPN with your Ubiquiti EdgeRouter.
Turning Atlassian JIRA into a CRM
Here at Member.buzz, we use Atlassian JIRA to track our features, bugs, and incoming requests from users through our Support Site. So when it came to choosing a CRM, we wanted to find one that integrated nicely with the rest of our infrastructure.Our first thought was to try out some of the existing JIRA CRM plugins. Here are the ones we tried out:CRM for JIRAAtlas CRMKanoah CRMAlthough there were definitely some interesting features among these options, there was nothing substantial enough to make us want to choose a specific one. We wanted something simple, yet well-integrated into what we already had
C-Level Security: When your team uses military analogies, are they using the wrong narrative?
For years, I have bristled when people would use medieval military descriptions in an attempt to convey concepts within the Network Security business. Bastions, Firewalls, Moats, Drawbridges, Countermeasures; all of these descriptions give way to a more accurate and detailed explanation of what was really taking place.
Using a Lenovo P51 Laptop with an Airplane Power Supply
The Lenovo P51 Laptop comes with a huge 170 watt Power Supply. However, airplane power supplies provide a maximum of somewhere between 75-100 watts. If you plugin a power supply requiring more watts, the circuit breaker will short out and the power will stop flowing.