JayRHa / EndpointAnalyticsRemediationScripts

MIT License
338 stars 74 forks source link

install all pending windows updates #9

Open JayRHa opened 1 year ago

najki78 commented 1 year ago

I have just finished a script that creates a scheduled task which runs Windows Update and then auto-reboot. I will polish it an create a pull request. Meanwhile, the core code:

# NuGet
$packageprovider = Get-PackageProvider -Name nuget -ListAvailable -Verbose -ErrorAction SilentlyContinue

# If not installed, download and install it from PSGallery repository
if (-not $packageprovider) {
    # Install NuGet provider if needed
    Install-PackageProvider -Name NuGet -Scope AllUsers -Verbose -Force -confirm:$false -ErrorAction SilentlyContinue 
}

Import-PackageProvider nuget -Verbose -Force -ErrorAction SilentlyContinue

# Check if PSWindowsUpdate module is already installed
$module = Get-Module -Name PSWindowsUpdate -ListAvailable -Verbose -ErrorAction SilentlyContinue

# If not installed, download and install it from PSGallery repository
if (-not $module) {
    # Install PSWindowsUpdate module for all users
    Install-Module -Name PSWindowsUpdate -Scope AllUsers -AllowClobber -Verbose  -Force -confirm:$false -ErrorAction SilentlyContinue
}

# Import PSWindowsUpdate module
Import-Module -Name PSWindowsUpdate -Scope Global -Verbose -ErrorAction SilentlyContinue

Write-Host "WindowsUpdate service"
$WindowsUpdateService = Get-Service -Name wuauserv -Verbose -ErrorAction SilentlyContinue

if( $WindowsUpdateService.StartType -eq "Disabled"){
    Set-Service -Name wuauserv -StartupType Manual -ErrorAction SilentlyContinue
}

if( $WindowsUpdateService.Status -ne "Running"){
    Start-Service -Name wuauserv -ErrorAction SilentlyContinue
}

# to exclude drivers, use parameter -NotCategory "Drivers"
Get-WindowsUpdate -NotCategory "Drivers" -Download -AcceptAll -Verbose -ErrorAction SilentlyContinue -Silent
Install-WindowsUpdate -NotCategory "Drivers" -AcceptAll -AutoReboot -Verbose -ErrorAction SilentlyContinue

Or alternatively, to include check if reboot is necessary:

Install-WindowsUpdate -AcceptAll -NoRestart -AutoReboot -Verbose -ErrorAction SilentlyContinue 
# check if Reboot is Required, if yes, Restart-Computer -Force
if ( (Get-WURebootStatus).RebootRequired ) { Restart-Computer -Force }