Last active
November 13, 2016 01:53
-
-
Save PlagueHO/3dd091d45db5800775321fbacfeaf479 to your computer and use it in GitHub Desktop.
Update multiple Windows Server 2016 TP4+ Nano Servers remotely using CIM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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