Skip to content

Instantly share code, notes, and snippets.

@PlagueHO
Last active November 13, 2016 01:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PlagueHO/3dd091d45db5800775321fbacfeaf479 to your computer and use it in GitHub Desktop.
Save PlagueHO/3dd091d45db5800775321fbacfeaf479 to your computer and use it in GitHub Desktop.
Update multiple Windows Server 2016 TP4+ Nano Servers remotely using CIM
function Get-AvailableUpdates {
[CmdletBinding()]
param (
[PSCredential] $Credential = (Get-Credential -Message 'Credentials to use to update Servers'),
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[String[]] $Servers,
[Switch] $Install,
[Switch] $Restart
)
$servers | foreach-object {
$session = New-CimSession `
-ComputerName $_ `
-Credential $credential
$instance = New-CimInstance `
-Namespace root/Microsoft/Windows/WindowsUpdate `
-ClassName MSFT_WUOperationsSession `
-CimSession $session
# Due to a bug in CIM on Nano Server (TP4 and TP5) an error is returned when
# there are no available updates.
# We use ErrorAction SilentlyContinue to ignore this (DON'T do this in a production script!!!!)
$scanResults = @($Instance | Invoke-CimMethod `
-MethodName ScanForUpdates `
-Arguments @{SearchCriteria="IsInstalled=0";OnlineScan=$true} `
-CimSession $session `
-errorAction SilentlyContinue)
if ($scanResults)
{
"$_ has $($scanResults.Count) updates to be installed:"
if ($install)
{
$installResult = $Instance | Invoke-CimMethod `
-MethodName ApplyApplicableUpdates `
-CimSession $Session
if ($installResult.ReturnValue -eq 0)
{
'Updates were installed successfully:'
$scanResults.Updates
if ($Restart)
{
"Restarting $_"
Invoke-Command `
-ComputerName $_ `
-Credential $credential `
-ScriptBlock { Restart-Computer }
}
else
{
'You may need to reboot this server for update installation to complete.'
}
}
else
{
'An error occurred installing updates:'
$installResult
}
}
else
{
'Set -Install flag to install updates'
$scanResults.Updates
} # if
}
else
{
"$_ has no updates to be installed."
} # if
Remove-CimSession `
-CimSession $session
} # foreach-object
} # function Get-AvailableUpdates
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment