win-updates.ps1 8.27 KB
Newer Older
1
param($global:RestartRequired=0,
2
        $global:MoreUpdates=0,
3
        $global:MaxCycles=5,
4
        $MaxUpdatesPerCycle=500)
5
6

function Check-ContinueRestartOrEnd() {
7
8
9
    $RegistryKey = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"
    $RegistryEntry = "InstallWindowsUpdates"
    switch ($global:RestartRequired) {
Stefan Scherer's avatar
Stefan Scherer committed
10
        0 {
11
12
13
14
15
            $prop = (Get-ItemProperty $RegistryKey).$RegistryEntry
            if ($prop) {
                Write-Host "Restart Registry Entry Exists - Removing It"
                Remove-ItemProperty -Path $RegistryKey -Name $RegistryEntry -ErrorAction SilentlyContinue
            }
Stefan Scherer's avatar
Stefan Scherer committed
16

17
18
            Write-Host "No Restart Required"
            Check-WindowsUpdates
19

20
21
22
23
            if (($global:MoreUpdates -eq 1) -and ($script:Cycles -le $global:MaxCycles)) {
                Install-WindowsUpdates
            } elseif ($script:Cycles -gt $global:MaxCycles) {
                Write-Host "Exceeded Cycle Count - Stopping"
24
                Invoke-Expression "a:\openssh.ps1 -AutoStart"
Stefan Scherer's avatar
Stefan Scherer committed
25
            } else {
26
                Write-Host "Done Installing Windows Updates"
27
                Invoke-Expression "a:\openssh.ps1 -AutoStart"
28
29
30
31
32
33
            }
        }
        1 {
            $prop = (Get-ItemProperty $RegistryKey).$RegistryEntry
            if (-not $prop) {
                Write-Host "Restart Registry Entry Does Not Exist - Creating It"
34
                Set-ItemProperty -Path $RegistryKey -Name $RegistryEntry -Value "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -File $($script:ScriptPath) -MaxUpdatesPerCycle $($MaxUpdatesPerCycle)"
35
36
37
            } else {
                Write-Host "Restart Registry Entry Exists Already"
            }
Stefan Scherer's avatar
Stefan Scherer committed
38

39
40
41
            Write-Host "Restart Required - Restarting..."
            Restart-Computer
        }
42
43
        default {
            Write-Host "Unsure If A Restart Is Required"
44
45
            break
        }
46
47
48
49
    }
}

function Install-WindowsUpdates() {
50
    $script:Cycles++
51
    Write-Host "Evaluating Available Updates with limit of $($MaxUpdatesPerCycle):"
52
    $UpdatesToDownload = New-Object -ComObject 'Microsoft.Update.UpdateColl'
53
    $script:i = 0;
Ken Sykora's avatar
Ken Sykora committed
54
    $CurrentUpdates = $SearchResult.Updates | Select-Object
55
    while($script:i -lt $CurrentUpdates.Count -and $script:CycleUpdateCount -lt $MaxUpdatesPerCycle) {
Ken Sykora's avatar
Ken Sykora committed
56
        $Update = $CurrentUpdates[$script:i]
57
58
59
60
61
62
63
64
65
        if (($Update -ne $null) -and (!$Update.IsDownloaded)) {
            [bool]$addThisUpdate = $false
            if ($Update.InstallationBehavior.CanRequestUserInput) {
                Write-Host "> Skipping: $($Update.Title) because it requires user input"
            } else {
                if (!($Update.EulaAccepted)) {
                    Write-Host "> Note: $($Update.Title) has a license agreement that must be accepted. Accepting the license."
                    $Update.AcceptEula()
                    [bool]$addThisUpdate = $true
66
                    $script:CycleUpdateCount++
67
68
                } else {
                    [bool]$addThisUpdate = $true
69
                    $script:CycleUpdateCount++
70
71
                }
            }
Stefan Scherer's avatar
Stefan Scherer committed
72

73
74
75
76
            if ([bool]$addThisUpdate) {
                Write-Host "Adding: $($Update.Title)"
                $UpdatesToDownload.Add($Update) |Out-Null
            }
Stefan Scherer's avatar
Stefan Scherer committed
77
        }
78
        $script:i++
79
    }
80

81
82
83
84
    if ($UpdatesToDownload.Count -eq 0) {
        Write-Host "No Updates To Download..."
    } else {
        Write-Host 'Downloading Updates...'
85
86
87
88
89
90
91
92
93
94
95
96
97
98
        $ok = 0;
        while (! $ok) {
            try {
                $Downloader = $UpdateSession.CreateUpdateDownloader()
                $Downloader.Updates = $UpdatesToDownload
                $Downloader.Download()
                $ok = 1;
            } catch {
                Write-Host $_.Exception | Format-List -force
                Write-Host "Error downloading updates. Retrying in 30s."
                $script:attempts = $script:attempts + 1
                Start-Sleep -s 30
            }
        }
99
    }
Stefan Scherer's avatar
Stefan Scherer committed
100

101
102
103
104
105
106
107
    $UpdatesToInstall = New-Object -ComObject 'Microsoft.Update.UpdateColl'
    [bool]$rebootMayBeRequired = $false
    Write-Host 'The following updates are downloaded and ready to be installed:'
    foreach ($Update in $SearchResult.Updates) {
        if (($Update.IsDownloaded)) {
            Write-Host "> $($Update.Title)"
            $UpdatesToInstall.Add($Update) |Out-Null
108

109
110
111
112
113
            if ($Update.InstallationBehavior.RebootBehavior -gt 0){
                [bool]$rebootMayBeRequired = $true
            }
        }
    }
Stefan Scherer's avatar
Stefan Scherer committed
114

115
116
117
118
    if ($UpdatesToInstall.Count -eq 0) {
        Write-Host 'No updates available to install...'
        $global:MoreUpdates=0
        $global:RestartRequired=0
119
        Invoke-Expression "a:\openssh.ps1 -AutoStart"
120
        break
121
122
    }

123
124
125
126
    if ($rebootMayBeRequired) {
        Write-Host 'These updates may require a reboot'
        $global:RestartRequired=1
    }
Stefan Scherer's avatar
Stefan Scherer committed
127

128
    Write-Host 'Installing updates...'
129

130
131
132
    $Installer = $script:UpdateSession.CreateUpdateInstaller()
    $Installer.Updates = $UpdatesToInstall
    $InstallationResult = $Installer.Install()
Stefan Scherer's avatar
Stefan Scherer committed
133

134
135
136
137
138
139
140
141
    Write-Host "Installation Result: $($InstallationResult.ResultCode)"
    Write-Host "Reboot Required: $($InstallationResult.RebootRequired)"
    Write-Host 'Listing of updates installed and individual installation results:'
    if ($InstallationResult.RebootRequired) {
        $global:RestartRequired=1
    } else {
        $global:RestartRequired=0
    }
Stefan Scherer's avatar
Stefan Scherer committed
142

143
144
145
146
    for($i=0; $i -lt $UpdatesToInstall.Count; $i++) {
        New-Object -TypeName PSObject -Property @{
            Title = $UpdatesToInstall.Item($i).Title
            Result = $InstallationResult.GetUpdateResult($i).ResultCode
147
        }
148
    }
Stefan Scherer's avatar
Stefan Scherer committed
149

150
    Check-ContinueRestartOrEnd
151
}
152

153
function Check-WindowsUpdates() {
154
155
    Write-Host "Checking For Windows Updates"
    $Username = $env:USERDOMAIN + "\" + $env:USERNAME
Stefan Scherer's avatar
Stefan Scherer committed
156

157
    New-EventLog -Source $ScriptName -LogName 'Windows Powershell' -ErrorAction SilentlyContinue
Stefan Scherer's avatar
Stefan Scherer committed
158

159
    $Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nStarted: " + (Get-Date).toString()
160

161
162
    Write-EventLog -LogName 'Windows Powershell' -Source $ScriptName -EventID "104" -EntryType "Information" -Message $Message
    Write-Host $Message
163

164
    $script:UpdateSearcher = $script:UpdateSession.CreateUpdateSearcher()
165
166
167
168
169
170
171
172
    $script:successful = $FALSE
    $script:attempts = 0
    $script:maxAttempts = 12
    while(-not $script:successful -and $script:attempts -lt $script:maxAttempts) {
        try {
            $script:SearchResult = $script:UpdateSearcher.Search("IsInstalled=0 and Type='Software' and IsHidden=0")
            $script:successful = $TRUE
        } catch {
Ken Sykora's avatar
Ken Sykora committed
173
174
            Write-Host $_.Exception | Format-List -force
            Write-Host "Search call to UpdateSearcher was unsuccessful. Retrying in 10s."
175
176
177
178
179
            $script:attempts = $script:attempts + 1
            Start-Sleep -s 10
        }
    }

180
    if ($SearchResult.Updates.Count -ne 0) {
181
182
183
184
185
186
187
188
189
190
191
192
193
        $Message = "There are " + $SearchResult.Updates.Count + " more updates."
        Write-Host $Message
        try {
            $script:SearchResult.Updates |Select-Object -Property Title, Description, SupportUrl, UninstallationNotes, RebootRequired, EulaAccepted |Format-List
            $global:MoreUpdates=1
        } catch {
            Write-Host $_.Exception | Format-List -force
            Write-Host "Showing SearchResult was unsuccessful. Rebooting."
            $global:RestartRequired=1
            $global:MoreUpdates=0
            Check-ContinueRestartOrEnd
            Restart-Computer
        }
194
195
196
197
198
    } else {
        Write-Host 'There are no applicable updates'
        $global:RestartRequired=0
        $global:MoreUpdates=0
    }
199
200
201
202
203
204
205
206
207
}

$script:ScriptName = $MyInvocation.MyCommand.ToString()
$script:ScriptPath = $MyInvocation.MyCommand.Path
$script:UpdateSession = New-Object -ComObject 'Microsoft.Update.Session'
$script:UpdateSession.ClientApplicationID = 'Packer Windows Update Installer'
$script:UpdateSearcher = $script:UpdateSession.CreateUpdateSearcher()
$script:SearchResult = New-Object -ComObject 'Microsoft.Update.UpdateColl'
$script:Cycles = 0
208
$script:CycleUpdateCount = 0
209
210
211

Check-WindowsUpdates
if ($global:MoreUpdates -eq 1) {
212
    Install-WindowsUpdates
213
} else {
214
    Check-ContinueRestartOrEnd
Stefan Scherer's avatar
Stefan Scherer committed
215
}