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

6
7
8
9
10
11
12
13
14
$Logfile = "C:\Windows\Temp\win-updates.log"

function LogWrite {
   Param ([string]$logstring)
   $now = Get-Date -format s
   Add-Content $Logfile -value "$now $logstring"
   Write-Host $logstring
}

15
function Check-ContinueRestartOrEnd() {
16
17
18
    $RegistryKey = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"
    $RegistryEntry = "InstallWindowsUpdates"
    switch ($global:RestartRequired) {
Stefan Scherer's avatar
Stefan Scherer committed
19
        0 {
20
21
            $prop = (Get-ItemProperty $RegistryKey).$RegistryEntry
            if ($prop) {
22
                LogWrite "Restart Registry Entry Exists - Removing It"
23
24
                Remove-ItemProperty -Path $RegistryKey -Name $RegistryEntry -ErrorAction SilentlyContinue
            }
Stefan Scherer's avatar
Stefan Scherer committed
25

26
            LogWrite "No Restart Required"
27
            Check-WindowsUpdates
28

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

48
            LogWrite "Restart Required - Restarting..."
49
50
            Restart-Computer
        }
51
        default {
52
            LogWrite "Unsure If A Restart Is Required"
53
54
            break
        }
55
56
57
58
    }
}

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

82
            if ([bool]$addThisUpdate) {
83
                LogWrite "Adding: $($Update.Title)"
84
85
                $UpdatesToDownload.Add($Update) |Out-Null
            }
Stefan Scherer's avatar
Stefan Scherer committed
86
        }
87
        $script:i++
88
    }
89

90
    if ($UpdatesToDownload.Count -eq 0) {
91
        LogWrite "No Updates To Download..."
92
    } else {
93
        LogWrite 'Downloading Updates...'
94
95
96
97
98
99
100
101
        $ok = 0;
        while (! $ok) {
            try {
                $Downloader = $UpdateSession.CreateUpdateDownloader()
                $Downloader.Updates = $UpdatesToDownload
                $Downloader.Download()
                $ok = 1;
            } catch {
102
103
                LogWrite $_.Exception | Format-List -force
                LogWrite "Error downloading updates. Retrying in 30s."
104
105
106
107
                $script:attempts = $script:attempts + 1
                Start-Sleep -s 30
            }
        }
108
    }
Stefan Scherer's avatar
Stefan Scherer committed
109

110
111
    $UpdatesToInstall = New-Object -ComObject 'Microsoft.Update.UpdateColl'
    [bool]$rebootMayBeRequired = $false
112
    LogWrite 'The following updates are downloaded and ready to be installed:'
113
114
    foreach ($Update in $SearchResult.Updates) {
        if (($Update.IsDownloaded)) {
115
            LogWrite "> $($Update.Title)"
116
            $UpdatesToInstall.Add($Update) |Out-Null
117

118
119
120
121
122
            if ($Update.InstallationBehavior.RebootBehavior -gt 0){
                [bool]$rebootMayBeRequired = $true
            }
        }
    }
Stefan Scherer's avatar
Stefan Scherer committed
123

124
    if ($UpdatesToInstall.Count -eq 0) {
125
        LogWrite 'No updates available to install...'
126
127
        $global:MoreUpdates=0
        $global:RestartRequired=0
128
        Invoke-Expression "a:\openssh.ps1 -AutoStart"
129
        break
130
131
    }

132
    if ($rebootMayBeRequired) {
133
        LogWrite 'These updates may require a reboot'
134
135
        $global:RestartRequired=1
    }
Stefan Scherer's avatar
Stefan Scherer committed
136

137
    LogWrite 'Installing updates...'
138

139
140
141
    $Installer = $script:UpdateSession.CreateUpdateInstaller()
    $Installer.Updates = $UpdatesToInstall
    $InstallationResult = $Installer.Install()
Stefan Scherer's avatar
Stefan Scherer committed
142

143
144
145
    LogWrite "Installation Result: $($InstallationResult.ResultCode)"
    LogWrite "Reboot Required: $($InstallationResult.RebootRequired)"
    LogWrite 'Listing of updates installed and individual installation results:'
146
147
148
149
150
    if ($InstallationResult.RebootRequired) {
        $global:RestartRequired=1
    } else {
        $global:RestartRequired=0
    }
Stefan Scherer's avatar
Stefan Scherer committed
151

152
153
154
155
    for($i=0; $i -lt $UpdatesToInstall.Count; $i++) {
        New-Object -TypeName PSObject -Property @{
            Title = $UpdatesToInstall.Item($i).Title
            Result = $InstallationResult.GetUpdateResult($i).ResultCode
156
        }
157
158
        LogWrite "Item: " $UpdatesToInstall.Item($i).Title
        LogWrite "Result: " $InstallationResult.GetUpdateResult($i).ResultCode;
159
    }
Stefan Scherer's avatar
Stefan Scherer committed
160

161
    Check-ContinueRestartOrEnd
162
}
163

164
function Check-WindowsUpdates() {
165
    LogWrite "Checking For Windows Updates"
166
    $Username = $env:USERDOMAIN + "\" + $env:USERNAME
Stefan Scherer's avatar
Stefan Scherer committed
167

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

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

172
    Write-EventLog -LogName 'Windows Powershell' -Source $ScriptName -EventID "104" -EntryType "Information" -Message $Message
173
    LogWrite $Message
174

175
    $script:UpdateSearcher = $script:UpdateSession.CreateUpdateSearcher()
176
177
178
179
180
181
182
183
    $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 {
184
185
            LogWrite $_.Exception | Format-List -force
            LogWrite "Search call to UpdateSearcher was unsuccessful. Retrying in 10s."
186
187
188
189
190
            $script:attempts = $script:attempts + 1
            Start-Sleep -s 10
        }
    }

191
    if ($SearchResult.Updates.Count -ne 0) {
192
        $Message = "There are " + $SearchResult.Updates.Count + " more updates."
193
        LogWrite $Message
194
        try {
bigwave's avatar
bigwave committed
195
196
197
198
199
200
            for($i=0; $i -lt $script:SearchResult.Updates.Count; $i++) {
              LogWrite $script:SearchResult.Updates.Item($i).Title
              LogWrite $script:SearchResult.Updates.Item($i).Description
              LogWrite $script:SearchResult.Updates.Item($i).RebootRequired
              LogWrite $script:SearchResult.Updates.Item($i).EulaAccepted
          }
201
202
            $global:MoreUpdates=1
        } catch {
203
204
            LogWrite $_.Exception | Format-List -force
            LogWrite "Showing SearchResult was unsuccessful. Rebooting."
205
206
207
            $global:RestartRequired=1
            $global:MoreUpdates=0
            Check-ContinueRestartOrEnd
208
            LogWrite "Show never happen to see this text!"
209
210
            Restart-Computer
        }
211
    } else {
212
        LogWrite 'There are no applicable updates'
213
214
215
        $global:RestartRequired=0
        $global:MoreUpdates=0
    }
216
217
218
219
220
221
222
223
224
}

$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
225
$script:CycleUpdateCount = 0
226
227
228

Check-WindowsUpdates
if ($global:MoreUpdates -eq 1) {
229
    Install-WindowsUpdates
230
} else {
231
    Check-ContinueRestartOrEnd
Stefan Scherer's avatar
Stefan Scherer committed
232
}