├── LICENSE ├── README.md └── WindowsUpdates ├── Tests └── WindowsUpdates.Tests.ps1 ├── WindowsUpdates.psd1 └── WindowsUpdates.psm1 /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WindowsUpdates 2 | 3 | A PowerShell Module for automated Windows Updates Management, which will offer: 4 | 5 | - Updates' retrieval 6 | - Updates' installation 7 | 8 | # How to use WindowsUpdates 9 | 10 | ```powershell 11 | Import-Module WindowsUpdates 12 | 13 | $updates = Get-WindowsUpdate 14 | if ($updates) { 15 | Install-WindowsUpdate $updates 16 | if (Get-RebootRequired) { 17 | Restart-Computer -Force 18 | } 19 | } 20 | ``` 21 | # If you want to exclude KBIDs and updates for specific hardware ID's 22 | 23 | ```powershell 24 | Import-Module WindowsUpdates 25 | 26 | $updates = Get-WindowsUpdate -Verbose -ExcludeKBId @("KB2267602") -ExcludeHardwareId @("{084f01fa-e634-4d77-83ee-074817c03581}") 27 | ``` 28 | 29 | ## Compatibility 30 | 31 | The WindowsUpdates module is compatible with PowerShell v2 or newer and tested with Windows version >= 6.1(Windows 7/2008R2 or newer). 32 | 33 | ## How to run tests 34 | 35 | You will need pester on your system. It should already be installed on your system if you are running Windows 10. If it is not: 36 | 37 | ```powershell 38 | Install-Package Pester 39 | ``` 40 | 41 | Running the actual tests: 42 | 43 | ```powershell 44 | powershell.exe -NonInteractive {Invoke-Pester} 45 | ``` 46 | 47 | This will run all tests without polluting your current shell environment. The -NonInteractive flag will make sure that any test that checks for mandatory parameters will not block the tests if run in an interactive session. This is not needed if you run this in a CI. 48 | 49 | -------------------------------------------------------------------------------- /WindowsUpdates/Tests/WindowsUpdates.Tests.ps1: -------------------------------------------------------------------------------- 1 | $here = Split-Path -Parent $MyInvocation.MyCommand.Path 2 | $moduleHome = Split-Path -Parent $here 3 | $moduleRoot = Split-Path -Parent $moduleHome 4 | 5 | $modulePath = ${env:PSModulePath}.Split(";") 6 | if (!($moduleRoot -in $modulePath)){ 7 | $env:PSModulePath += ";$moduleRoot" 8 | } 9 | $savedEnv = [System.Environment]::GetEnvironmentVariables() 10 | 11 | function Clear-Environment { 12 | $current = [System.Environment]::GetEnvironmentVariables() 13 | foreach($i in $savedEnv.GetEnumerator()) { 14 | [System.Environment]::SetEnvironmentVariable($i.Name, $i.Value, "Process") 15 | } 16 | $current = [System.Environment]::GetEnvironmentVariables() 17 | foreach ($i in $current.GetEnumerator()){ 18 | if(!$savedEnv[$i.Name]){ 19 | [System.Environment]::SetEnvironmentVariable($i.Name, $null, "Process") 20 | } 21 | } 22 | } 23 | 24 | function Compare-Objects ($first, $last) { 25 | (Compare-Object $first $last -SyncWindow 0).Length -eq 0 26 | } 27 | 28 | function Compare-ScriptBlocks { 29 | Param( 30 | [System.Management.Automation.ScriptBlock]$scrBlock1, 31 | [System.Management.Automation.ScriptBlock]$scrBlock2 32 | ) 33 | 34 | $sb1 = $scrBlock1.ToString() 35 | $sb2 = $scrBlock2.ToString() 36 | 37 | return ($sb1.CompareTo($sb2) -eq 0) 38 | } 39 | 40 | function Add-FakeObjProperty ([ref]$obj, $name, $value) { 41 | Add-Member -InputObject $obj.value -MemberType NoteProperty ` 42 | -Name $name -Value $value 43 | } 44 | 45 | function Add-FakeObjProperties ([ref]$obj, $fakeProperties, $value) { 46 | foreach ($prop in $fakeProperties) { 47 | Add-Member -InputObject $obj.value -MemberType NoteProperty ` 48 | -Name $prop -Value $value 49 | } 50 | } 51 | 52 | function Add-FakeObjMethod ([ref]$obj, $name) { 53 | Add-Member -InputObject $obj.value -MemberType ScriptMethod ` 54 | -Name $name -Value { return 0 } 55 | } 56 | 57 | function Add-FakeObjMethods ([ref]$obj, $fakeMethods) { 58 | foreach ($method in $fakeMethods) { 59 | Add-Member -InputObject $obj.value -MemberType ScriptMethod ` 60 | -Name $method -Value { return 0 } 61 | } 62 | } 63 | 64 | function Compare-Arrays ($arr1, $arr2) { 65 | return (((Compare-Object $arr1 $arr2).InputObject).Length -eq 0) 66 | } 67 | 68 | function Compare-HashTables ($tab1, $tab2) { 69 | if ($tab1.Count -ne $tab2.Count) { 70 | return $false 71 | } 72 | foreach ($i in $tab1.Keys) { 73 | if (($tab2.ContainsKey($i) -eq $false) -or ($tab1[$i] -ne $tab2[$i])) { 74 | return $false 75 | } 76 | } 77 | return $true 78 | } 79 | 80 | Import-Module WindowsUpdates 81 | 82 | Describe "Test Get-WindowsUpdate" { 83 | AfterEach { 84 | Clear-Environment 85 | } 86 | 87 | Mock Get-UpdateSearcher -Verifiable -ModuleName WindowsUpdates ` 88 | { 89 | $updateSearcherMock = New-Object -TypeName PSObject 90 | Add-Member -InputObject ([ref]$updateSearcherMock).value ` 91 | -MemberType NoteProperty -Name "ServerSelection" -Value -1 92 | return $updateSearcherMock 93 | } 94 | 95 | Mock Get-LocalUpdates -Verifiable -ModuleName WindowsUpdates ` 96 | { 97 | return @{ 98 | "Updates"=@("update"); 99 | "Count"=1 100 | } 101 | } 102 | 103 | Mock Add-WindowsUpdateToCollection -Verifiable -ModuleName WindowsUpdates ` 104 | { 105 | return @{ 106 | "Updates"=@("update"); 107 | "Count"=1 108 | } 109 | } 110 | 111 | It "Should return fake updates" { 112 | Compare-HashTables (Get-WindowsUpdate) @{ 113 | "Updates"=@("update"); 114 | "Count"=1 115 | } | Should Be $true 116 | } 117 | } 118 | 119 | Describe "Test Get-RebootRequired" { 120 | AfterEach { 121 | Clear-Environment 122 | } 123 | 124 | Context "On reboot true" { 125 | Mock Get-UpdateRebootRequired -Verifiable -ModuleName WindowsUpdates ` 126 | { return $true } 127 | Mock Get-RegKeyRebootRequired -Verifiable -ModuleName WindowsUpdates ` 128 | { return $true } 129 | 130 | $rebootStatus = Get-RebootRequired 131 | It "Should return true" { 132 | $rebootStatus | Should Be $true 133 | } 134 | It "Should verify all methods" { 135 | Assert-MockCalled Get-UpdateRebootRequired -Exactly 1 ` 136 | -ModuleName WindowsUpdates 137 | Assert-MockCalled Get-RegKeyRebootRequired -Exactly 0 ` 138 | -ModuleName WindowsUpdates 139 | } 140 | } 141 | 142 | Context "On reboot false" { 143 | Mock Get-UpdateRebootRequired -Verifiable -ModuleName WindowsUpdates ` 144 | { return $false } 145 | Mock Get-RegKeyRebootRequired -Verifiable -ModuleName WindowsUpdates ` 146 | { return $false } 147 | 148 | $rebootStatus = Get-RebootRequired 149 | It "Should return false" { 150 | $rebootStatus | Should Be $false 151 | } 152 | It "Should verify all methods" { 153 | Assert-MockCalled Get-UpdateRebootRequired -Exactly 1 ` 154 | -ModuleName WindowsUpdates 155 | Assert-MockCalled Get-RegKeyRebootRequired -Exactly 1 ` 156 | -ModuleName WindowsUpdates 157 | } 158 | } 159 | } -------------------------------------------------------------------------------- /WindowsUpdates/WindowsUpdates.psd1: -------------------------------------------------------------------------------- 1 | # Copyright 2016 Cloudbase Solutions Srl 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | # 15 | # Module manifest for module 'WindowsUpdates' 16 | # 17 | # Generated by: Adrian Vladu 18 | # 19 | # Generated on: 01/03/2016 20 | # 21 | 22 | @{ 23 | 24 | # Script module or binary module file associated with this manifest. 25 | NestedModules = 'WindowsUpdates.psm1' 26 | 27 | # Version number of this module. 28 | ModuleVersion = '0.1' 29 | 30 | # ID used to uniquely identify this module 31 | GUID = 'f0438e9b-e3a5-406f-856a-02fa047250d5' 32 | 33 | # Author of this module 34 | Author = 'Adrian Vladu' 35 | 36 | # Company or vendor of this module 37 | CompanyName = 'Cloudbase Solutions SRL' 38 | 39 | # Copyright statement for this module 40 | Copyright = '(c) 2016 Cloudbase Solutions SRL. All rights reserved.' 41 | 42 | # Description of the functionality provided by this module 43 | Description = 'PowerShell Module for automated Windows Updates Management' 44 | 45 | # Minimum version of the Windows PowerShell engine required by this module 46 | PowerShellVersion = '2.0' 47 | 48 | # Functions to export from this module 49 | FunctionsToExport = @( 50 | "Get-WindowsUpdate", 51 | "Get-RebootRequired", 52 | "Install-WindowsUpdate" 53 | ) 54 | # Cmdlets to export from this module 55 | CmdletsToExport = '*' 56 | 57 | # Variables to export from this module 58 | VariablesToExport = '*' 59 | 60 | } 61 | -------------------------------------------------------------------------------- /WindowsUpdates/WindowsUpdates.psm1: -------------------------------------------------------------------------------- 1 | # Copyright 2016 Cloudbase Solutions Srl 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | $ErrorActionPreference = "Stop" 15 | 16 | $UPDATE_SESSION_COM_CLASS = "Microsoft.Update.Session" 17 | $UPDATE_SYSTEM_INFO_COM_CLASS = "Microsoft.Update.SystemInfo" 18 | $UPDATE_COLL_COM_CLASS = "Microsoft.Update.UpdateColl" 19 | $SERVER_SELECTION_WINDOWS_UPDATE = 2 20 | $UPDATE_DOWNLOAD_STATUS_CODES = @{ 21 | 0 = "NotStarted" 22 | 1 = "InProgress" 23 | 2 = "Downloaded" 24 | 3 = "DownloadedWithErrors" 25 | 4 = "Failed" 26 | 5 = "Aborted" 27 | } 28 | $UPDATE_INSTALL_STATUS_CODES = @{ 29 | 0 = "NotStarted" 30 | 1 = "InProgress" 31 | 2 = "Installed" 32 | 3 = "InstalledWithErrors" 33 | 4 = "Failed" 34 | 5 = "Aborted" 35 | } 36 | 37 | function Write-UpdateInformation { 38 | Param( 39 | [Parameter(Mandatory=$true)] 40 | $Updates 41 | ) 42 | foreach ($update in $Updates) { 43 | Write-Host ("Update title: " + $update.Title) 44 | Write-Host ($update.Categories | Select-Object Name) 45 | Write-Host ("Update size: " + ([int]($update.MaxDownloadSize/1MB) + 1) + "MB") 46 | Write-Host "" 47 | } 48 | } 49 | 50 | function Get-UpdateSearcher { 51 | $updateSession = New-Object -ComObject $UPDATE_SESSION_COM_CLASS 52 | return $updateSession.CreateUpdateSearcher() 53 | } 54 | 55 | function Get-UpdateDownloader { 56 | $updateSession = New-Object -ComObject $UPDATE_SESSION_COM_CLASS 57 | return $updateSession.CreateUpdateDownloader() 58 | } 59 | 60 | function Get-LocalUpdates { 61 | Param( 62 | [Parameter(Mandatory=$true)] 63 | $UpdateSearcher, 64 | [Parameter(Mandatory=$true)] 65 | [string]$SearchCriteria 66 | ) 67 | try { 68 | $updatesResult = $updateSearcher.Search($searchCriteria) 69 | } catch [Exception]{ 70 | Write-Host "Failed to search for updates" 71 | throw 72 | } 73 | return $updatesResult 74 | } 75 | 76 | function Add-WindowsUpdateToCollection { 77 | Param( 78 | [Parameter(Mandatory=$true)] 79 | $Collection, 80 | [Parameter(Mandatory=$true)] 81 | $Update 82 | ) 83 | 84 | $Collection.Add($Update) | Out-Null 85 | } 86 | 87 | function Get-WindowsUpdate { 88 | <# 89 | .SYNOPSIS 90 | Get-WindowsUpdate is a command that will return the applicable updates to 91 | the Windows operating system. 92 | #> 93 | [CmdletBinding()] 94 | Param( 95 | [Parameter(Mandatory=$false)] 96 | [array]$ExcludeKBId=@(), 97 | [Parameter(Mandatory=$false)] 98 | [array]$ExcludeHardwareId=@() 99 | ) 100 | PROCESS { 101 | $updateSearcher = Get-UpdateSearcher 102 | # Set the update source server to Windows Update 103 | $updateSearcher.ServerSelection = $SERVER_SELECTION_WINDOWS_UPDATE 104 | # Set search criteria 105 | $searchCriteria = "( IsInstalled = 0 and IsHidden = 0)" 106 | $updateResult = Get-LocalUpdates -UpdateSearcher $updateSearcher ` 107 | -SearchCriteria $searchCriteria 108 | if (!$updateResult -or !$updateResult.Updates) { 109 | return 110 | } 111 | $updates = $updateResult.Updates 112 | $filteredUpdates = New-Object -ComObject $UPDATE_COLL_COM_CLASS 113 | for ($i=0; $i -lt $updates.Count; $i++) { 114 | $update = $updates.Item($i) 115 | $updateKBId = ($update.KBArticleIDs -join ", KB") 116 | if ($ExcludeKBId -contains ("KB" + $updateKBId)) { 117 | Write-Verbose ("Exclude update KB{0}" ` 118 | -f @($updateKBId)) 119 | } elseif ($ExcludeHardwareId -contains $update.DriverHardwareID) { 120 | Write-Verbose ("Exclude update: {0}" -f @($Title)) 121 | } else { 122 | Add-WindowsUpdateToCollection $filteredUpdates $update 123 | } 124 | } 125 | 126 | return $filteredUpdates 127 | } 128 | } 129 | 130 | function Get-RegKeyRebootRequired { 131 | $basePath = "HKLM:\\SOFTWARE\Microsoft\Windows\CurrentVersion\" 132 | $cbsRebootRequired = Get-Item -Path "${basePath}Component Based Servicing\RebootPending" ` 133 | -ErrorAction SilentlyContinue 134 | $auRebootRequired = Get-Item -Path "${basePath}\WindowsUpdate\Auto Update\RebootRequired" ` 135 | -ErrorAction SilentlyContinue 136 | return ($cbsRebootRequired -and $auRebootRequired) 137 | } 138 | 139 | function Get-UpdateRebootRequired { 140 | $systemInfo = New-Object -ComObject $UPDATE_SYSTEM_INFO_COM_CLASS 141 | return $systemInfo.RebootRequired 142 | } 143 | 144 | function Get-RebootRequired { 145 | <# 146 | .SYNOPSIS 147 | Get-RebootRequired is a command that will return the reboot required status 148 | of a Windows machine. This status check is necessary in order to know 149 | whether to perform a machine restart in order to continue to install the 150 | Windows updates. 151 | #> 152 | return ((Get-UpdateRebootRequired) -or (Get-RegKeyRebootRequired)) 153 | } 154 | 155 | function Install-WindowsUpdate { 156 | <# 157 | .SYNOPSIS 158 | Install-WindowsUpdate is a command that will install the updates given as 159 | a parameter on the Windows operating system. 160 | .Parameter Updates 161 | The required value can be obtained by running Get-WindowsUpdate 162 | #> 163 | [CmdletBinding()] 164 | Param( 165 | [Parameter( 166 | Position=0, 167 | Mandatory=$true, 168 | ValueFromPipeline=$true)] 169 | $Updates 170 | ) 171 | PROCESS { 172 | foreach ($update in $Updates) { 173 | $updateSize = ([int]($update.MaxDownloadSize/1MB) + 1) 174 | Write-Host ("Installing Update: {0} ({1}MB)" -f @($update.Title, $updateSize)) 175 | 176 | if ($update.EulaAccepted -eq 0) { 177 | Write-Host ("AcceptEula for Update: " + $update.Title) 178 | $update.AcceptEula() 179 | } 180 | 181 | $updateSession = New-Object -ComObject $UPDATE_SESSION_COM_CLASS 182 | $updateColl = New-Object -ComObject $UPDATE_COLL_COM_CLASS 183 | $updateColl.add($update) | Out-Null 184 | 185 | # DOWNLOAD UPDATE 186 | $updateDownloader = $updateSession.CreateUpdateDownloader() 187 | $updateDownloader.Updates = $updateColl 188 | $maxRetries = 5 189 | $retries = 0 190 | while ($retries -lt $maxRetries) { 191 | $downloadResult = $updateDownloader.Download() 192 | if ($downloadResult.ResultCode -ne 2) { 193 | $retries++ 194 | Write-Host "Failed to download update. Reason: " + ` 195 | $UPDATE_DOWNLOAD_STATUS_CODES[$downloadResult.ResultCode] 196 | } else { 197 | Write-Host "Update has been downloaded." 198 | break 199 | } 200 | } 201 | if ($retries -eq $maxRetries) { 202 | write-host "$retries" 203 | throw "Failed to download update." 204 | } 205 | 206 | # INSTALL UPDATE 207 | $updateInstaller = $updateSession.CreateUpdateInstaller() 208 | $updateInstaller.Updates = $updateColl 209 | $maxRetries = 5 210 | $retries = 0 211 | while ($retries -lt $maxRetries) { 212 | $installResult = $updateInstaller.Install() 213 | if ($installResult.ResultCode -ne 2) { 214 | $retries++ 215 | Write-Host "Failed to install update. Reason: " + ` 216 | $UPDATE_INSTALL_STATUS_CODES[$installResult.ResultCode] 217 | } else { 218 | Write-Host "Update has been installed." 219 | break 220 | } 221 | } 222 | if ($retries -eq $maxRetries) { 223 | write-host "$retries" 224 | throw "Failed to install update." 225 | } 226 | 227 | $updateColl.clear() 228 | } 229 | } 230 | } 231 | 232 | Export-ModuleMember -Function * -Alias * 233 | --------------------------------------------------------------------------------