Office-Update.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
<#PSScriptInfo
 
.VERSION 21.12.08
 
.GUID 72cb5483-744e-4a7d-bcad-e04462ea2c2e
 
.AUTHOR Mike Galvin Contact: mike@gal.vin / twitter.com/mikegalvin_ / discord.gg/5ZsnJ5k
 
.COMPANYNAME Mike Galvin
 
.COPYRIGHT (C) Mike Galvin. All rights reserved.
 
.TAGS Office 2019 365 Click-to-run C2R updates
 
.LICENSEURI
 
.PROJECTURI https://gal.vin/posts/automated-office-updates
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
#>


<#
    .SYNOPSIS
    Office Update Utility - Office Update Manager.
 
    .DESCRIPTION
    Checks for updates of Office 365/2019.
 
    To send a log file via e-mail using ssl and an SMTP password you must generate an encrypted password file.
    The password file is unique to both the user and machine.
 
    To create the password file run this command as the user and on the machine that will use the file:
 
    $creds = Get-Credential
    $creds.Password | ConvertFrom-SecureString | Set-Content C:\scripts\ps-script-pwd.txt
 
    .PARAMETER Office
    The folder containing the Office Deployment Tool (ODT).
 
    .PARAMETER Config
    The name of the configuration xml file for the Office Deployment Tool.
    It must be located in the same folder as the Office deployment tool.
 
    .PARAMETER Days
    The number of days that you wish to keep old update files for.
    If you do not configure this option, no old update files will be removed.
 
    .PARAMETER NoBanner
    Use this option to hide the ASCII art title in the console.
 
    .PARAMETER L
    The path to output the log file to.
    The file name will be Office-Update_YYYY-MM-dd_HH-mm-ss.log
    Do not add a trailing \ backslash.
 
    .PARAMETER Subject
    The subject line for the e-mail log. Encapsulate with single or double quotes.
    If no subject is specified, the default of "Office Update Utility Log" will be used.
 
    .PARAMETER SendTo
    The e-mail address the log should be sent to.
 
    .PARAMETER From
    The e-mail address the log should be sent from.
 
    .PARAMETER Smtp
    The DNS name or IP address of the SMTP server.
 
    .PARAMETER Port
    The Port that should be used for the SMTP server.
 
    .PARAMETER User
    The user account to authenticate to the SMTP server.
 
    .PARAMETER Pwd
    The txt file containing the encrypted password for SMTP authentication.
 
    .PARAMETER UseSsl
    Configures the utility to connect to the SMTP server using SSL.
 
    .EXAMPLE
    Office-Update.ps1 -Office \\Apps01\Software\Office365 -Config config-365-x64.xml -Days 30 -L C:\scripts\logs
    -Subject 'Server: Office Update' -SendTo me@contoso.com -From OffUpdate@contoso.com -Smtp exch01.contoso.com
    -User me@contoso.com -Pwd P@ssw0rd -UseSsl
 
    The above command will download any Office updates for the version and channel configured in config-365-x64.xml
    to the Office files directory \\Apps01\Software\Office365. Any update files older than 30 days will be removed.
    If the download is successful the log file will be output to C:\scripts\logs and e-mailed with a custom subject line.
#>


## Set up command line switches.
[CmdletBinding()]
Param(
    [parameter(Mandatory=$True)]
    [alias("Office")]
    [ValidateScript({Test-Path $_ -PathType 'Container'})]
    $OfficeSrc,
    [parameter(Mandatory=$True)]
    [alias("Config")]
    $Cfg,
    [alias("Days")]
    $Time,
    [alias("L")]
    $LogPath,
    [alias("Subject")]
    $MailSubject,
    [alias("SendTo")]
    $MailTo,
    [alias("From")]
    $MailFrom,
    [alias("Smtp")]
    $SmtpServer,
    [alias("Port")]
    $SmtpPort,
    [alias("User")]
    $SmtpUser,
    [alias("Pwd")]
    [ValidateScript({Test-Path -Path $_ -PathType Leaf})]
    $SmtpPwd,
    [switch]$UseSsl,
    [switch]$NoBanner)

If ($NoBanner -eq $False)
{
    Write-Host -Object ""
    Write-Host -ForegroundColor Yellow -BackgroundColor Black -Object " "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black -Object " ___ __ __ _ _ _ "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black -Object " /___\/ _|/ _(_) ___ ___ /\ /\ _ __ __| | __ _| |_ ___ "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black -Object " // // |_| |_| |/ __/ _ \ / / \ \ '_ \ / _ |/ _ | __/ _ \ "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black -Object " / \_//| _| _| | (_| __/ \ \_/ / |_) | (_| | (_| | || __/ "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black -Object " \___/ |_| |_| |_|\___\___| \___/| .__/ \__,_|\__,_|\__\___| "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black -Object " |_| "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black -Object " _ _ _ _ _ "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black -Object " /\ /\| |_(_) (_) |_ _ _ "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black -Object " / / \ \ __| | | | __| | | | 3 6 5 "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black -Object " \ \_/ / |_| | | | |_| |_| | 2 0 1 9 "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black -Object " \___/ \__|_|_|_|\__|\__, | Click-to-Run "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black -Object " |___/ "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black -Object " "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black -Object " Mike Galvin https://gal.vin Version 21.12.08 "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black -Object " "
    Write-Host -Object ""
}

## If logging is configured, start logging.
## If the log file already exists, clear it.
If ($LogPath)
{
    ## Make sure the log directory exists.
    $LogPathFolderT = Test-Path $LogPath

    If ($LogPathFolderT -eq $False)
    {
        New-Item $LogPath -ItemType Directory -Force | Out-Null
    }

    $LogFile = ("Office-Update_{0:yyyy-MM-dd_HH-mm-ss}.log" -f (Get-Date))
    $Log = "$LogPath\$LogFile"

    $LogT = Test-Path -Path $Log

    If ($LogT)
    {
        Clear-Content -Path $Log
    }

    Add-Content -Path $Log -Encoding ASCII -Value "$(Get-Date -Format "yyyy-MM-dd HH:mm:ss") [INFO] Log started"
}

## Function to get date in specific format.
Function Get-DateFormat
{
    Get-Date -Format "yyyy-MM-dd HH:mm:ss"
}

## Function for logging.
Function Write-Log($Type, $Evt)
{
    If ($Type -eq "Info")
    {
        If ($Null -ne $LogPath)
        {
            Add-Content -Path $Log -Encoding ASCII -Value "$(Get-DateFormat) [INFO] $Evt"
        }
        
        Write-Host -Object "$(Get-DateFormat) [INFO] $Evt"
    }

    If ($Type -eq "Succ")
    {
        If ($Null -ne $LogPath)
        {
            Add-Content -Path $Log -Encoding ASCII -Value "$(Get-DateFormat) [SUCCESS] $Evt"
        }

        Write-Host -ForegroundColor Green -Object "$(Get-DateFormat) [SUCCESS] $Evt"
    }

    If ($Type -eq "Err")
    {
        If ($Null -ne $LogPath)
        {
            Add-Content -Path $Log -Encoding ASCII -Value "$(Get-DateFormat) [ERROR] $Evt"
        }

        Write-Host -ForegroundColor Red -BackgroundColor Black -Object "$(Get-DateFormat) [ERROR] $Evt"
    }

    If ($Type -eq "Conf")
    {
        If ($Null -ne $LogPath)
        {
            Add-Content -Path $Log -Encoding ASCII -Value "$Evt"
        }

        Write-Host -ForegroundColor Cyan -Object "$Evt"
    }
}

## getting Windows Version info
$OSVMaj = [environment]::OSVersion.Version | Select-Object -expand major
$OSVMin = [environment]::OSVersion.Version | Select-Object -expand minor
$OSVBui = [environment]::OSVersion.Version | Select-Object -expand build
$OSV = "$OSVMaj" + "." + "$OSVMin" + "." + "$OSVBui"

##
## Display the current config and log if configured.
##

Write-Log -Type Conf -Evt "************ Running with the following config *************."
Write-Log -Type Conf -Evt "Utility Version:.......21.12.08"
Write-Log -Type Conf -Evt "Hostname:..............$Env:ComputerName."
Write-Log -Type Conf -Evt "Windows Version:.......$OSV."
Write-Log -Type Conf -Evt "Office folder:.........$OfficeSrc."
Write-Log -Type Conf -Evt "Config file:...........$Cfg."
Write-Log -Type Conf -Evt "Days to keep updates:..$Time days."

If ($Null -ne $LogPath)
{
    Write-Log -Type Conf -Evt "Logs directory:........$LogPath."
}

else {
    Write-Log -Type Conf -Evt "Logs directory:........No Config"
}

If ($MailTo)
{
    Write-Log -Type Conf -Evt "E-mail log to:.........$MailTo."
}

else {
    Write-Log -Type Conf -Evt "E-mail log to:.........No Config"
}

If ($MailFrom)
{
    Write-Log -Type Conf -Evt "E-mail log from:.......$MailFrom."
}

else {
    Write-Log -Type Conf -Evt "E-mail log from:.......No Config"
}

If ($MailSubject)
{
    Write-Log -Type Conf -Evt "E-mail subject:........$MailSubject."
}

else {
    Write-Log -Type Conf -Evt "E-mail subject:........Default"
}

If ($SmtpServer)
{
    Write-Log -Type Conf -Evt "SMTP server is:........$SmtpServer."
}

else {
    Write-Log -Type Conf -Evt "SMTP server is:........No Config"
}

If ($SmtpPort)
{
    Write-Log -Type Conf -Evt "SMTP Port:...............$SmtpPort."
}

else {
    Write-Log -Type Conf -Evt "SMTP Port:...............Default"
}

If ($SmtpUser)
{
    Write-Log -Type Conf -Evt "SMTP user is:..........$SmtpUser."
}

else {
    Write-Log -Type Conf -Evt "SMTP user is:..........No Config"
}

If ($SmtpPwd)
{
    Write-Log -Type Conf -Evt "SMTP pwd file:.........$SmtpPwd."
}

else {
    Write-Log -Type Conf -Evt "SMTP pwd file:.........No Config"
}

Write-Log -Type Conf -Evt "-UseSSL switch is:.....$UseSsl."
Write-Log -Type Conf -Evt "************************************************************"
Write-Log -Type Info -Evt "Process started"

##
## Display current config ends here.
##

#Run update process.
& $OfficeSrc\setup.exe /download $OfficeSrc\$Cfg

## Location of the office source files.
$UpdateFolder = "$OfficeSrc\Office\Data"

## Check the last write time of the office source files folder if it is greater than the previous day.
$Updated = (Get-ChildItem -Path $UpdateFolder | Where-Object CreationTime -gt (Get-Date).AddDays(-1)).Count

## If the Updated variable returns as not 0 then continue.
If ($Updated -ne 0)
{
    $VerName = Get-ChildItem -Path $UpdateFolder -Directory | Sort-Object LastWriteTime | Select-Object -last 1 | Select-Object -ExpandProperty Name
    Write-Log -Type Info -Evt "Office source files were updated."
    Write-Log -Type Info -Evt "Latest version is: $VerName"

    If ($Null -ne $Time)
    {
        $FilesToDel = Get-ChildItem -Path $UpdateFolder | Where-Object LastWriteTime –lt (Get-Date).AddDays(-$Time)

        If ($FilesToDel.count -ne 0)
        {
            Write-Log -Type Info -Evt "The following old Office files were removed:"
            Get-ChildItem -Path $UpdateFolder | Where-Object LastWriteTime –lt (Get-Date).AddDays(-$Time)
            Get-ChildItem -Path $UpdateFolder | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-$Time)} | Select-Object -Property Name, LastWriteTime | Format-Table -HideTableHeaders | Out-File -Append $Log -Encoding ASCII

            ## If configured, remove the old files.
            Get-ChildItem $UpdateFolder | Where-Object {$_.LastWriteTime –lt (Get-Date).AddDays(-$Time)} | Remove-Item -Recurse
        }
    }

    Write-Log -Type Info -Evt "Process finished"

    ## If logging is configured then finish the log file.
    If ($LogPath)
    {
        Add-Content -Path $Log -Encoding ASCII -Value "$(Get-Date -Format "yyyy-MM-dd HH:mm:ss") [INFO] Log finished"

        ## This whole block is for e-mail, if it is configured.
        If ($SmtpServer)
        {
            ## Default e-mail subject if none is configured.
            If ($Null -eq $MailSubject)
            {
                $MailSubject = "Office Update Utility Log"
            }

            ## Default Smtp Port if none is configured.
            If ($Null -eq $SmtpPort)
            {
                $SmtpPort = "25"
            }

            ## Setting the contents of the log to be the e-mail body.
            $MailBody = Get-Content -Path $Log | Out-String

            ## If an smtp password is configured, get the username and password together for authentication.
            ## If an smtp password is not provided then send the e-mail without authentication and obviously no SSL.
            If ($SmtpPwd)
            {
                $SmtpPwdEncrypt = Get-Content $SmtpPwd | ConvertTo-SecureString
                $SmtpCreds = New-Object System.Management.Automation.PSCredential -ArgumentList ($SmtpUser, $SmtpPwdEncrypt)

                ## If -ssl switch is used, send the email with SSL.
                ## If it isn't then don't use SSL, but still authenticate with the credentials.
                If ($UseSsl)
                {
                    Send-MailMessage -To $MailTo -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer -Port $SmtpPort -UseSsl -Credential $SmtpCreds
                }

                else {
                    Send-MailMessage -To $MailTo -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer -Port $SmtpPort -Credential $SmtpCreds
                }
            }

            else {
                Send-MailMessage -To $MailTo -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer -Port $SmtpPort
            }
        }
    }
}

Write-Log -Type Info -Evt "No updates."
Write-Log -Type Info -Evt "Process finished"

## End