forked from Sorrowfulgod/UpdateService
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Update-Servers.ps1
801 lines (696 loc) · 26.9 KB
/
Update-Servers.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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
<#
.NOTES
Copyright (c) Sergey Gruzdov. All rights reserved.
Update servers without services downtime
.SYNOPSIS
Update servers without services downtime
.DESCRIPTION
Update servers without services downtime. If no of Server* parameters specified - get servers list from AD
.PARAMETER ServerList
Comma-delitited list of servers for update
.PARAMETER SkipServers
Comma-delitited list of skipped servers
.PARAMETER ServerListFile
File contained list of servers for update (one server per line)
.PARAMETER DontStopOnError
Don't stop update on errors
.PARAMETER OnlyCheckReebot
Check if reboot needed. Reboot if necessary
.PARAMETER RebootServer
Perform server rebooot with mainternance mode
.PARAMETER NoPostStep
Update server and leave in maintenance mode
.PARAMETER OnlyPostStep
Exit server maintenance mode
.PARAMETER SMTPServer
SMTP server for notifications
.PARAMETER SMTPFrom
From
.PARAMETER SMTPTo
To
#>
param(
[string[]]
$ServerList,
[string[]]
$SkipServers,
[string]
[ValidateNotNullOrEmpty()]
[ValidateScript({ Test-Path $(Resolve-Path $_) })]
$ServerListFile,
[string]
$SMTPServer = $null,
[string]
$SMTPFrom = $null,
[string]
$SMTPTo = $null,
[switch]
$NoPostStep,
[switch]
$OnlyCheckReboot,
[switch]
$RebootServer,
[switch]
$OnlyPostStep,
[switch]
$OnlyShowList,
[switch]
$DontStopOnError = $false
)
function Log($message, $color = "Gray", [switch]$OnlyFile = $false, $Server)
{
$strOutput = "$([DateTime]::now.Tostring("dd-MM-yyyy HH:mm:ss")): $message"
if (!$onlyFile)
{
Write-Host $strOutput -ForegroundColor $([ConsoleColor]$color)
}
$strOutput | Out-File -FilePath $logFile -Append -Encoding ascii
if ($server)
{
$strOutput | Out-File -FilePath $($logPattern -f $server) -Append -Encoding ascii
}
}
function InvokeStep($serverName, $fileName, $arguments, $feature)
{
$usePSSession = $false
$saveArguments = $arguments
$stepResult = $null
$psSessionParams = @{}
if ($xmlConfig.Configuration.GlobalParams.PSSession -and $serverName -ne ".")
{
$rolePSSession = $xmlConfig.Configuration.GlobalParams.PSSession
$psSessionParams.Add("ComputerName", $serverName)
}
if ($feature -and $xmlConfig -ne $null)
{
$arguments = @()
$argumentsNames = @()
$rolesConfigration = $xmlConfig.Configuration.Role | ? rolename -eq $feature
$roleActionParams = $roleConfig.Param
if ($roleActionParams)
{
foreach($param in $roleActionParams)
{
$argumentsNames += $param.Name
if ($param.variable)
{
if ($serverName -eq "." -and $param.variable -eq '$serverName')
{
$varName = '$saveArguments'
}
else
{
$varName = $param.variable
}
Invoke-Expression "`$arg = $varName"
}
else
{
if ($param.Type -match "string")
{
Invoke-Expression "`$arg = `"$($param.Value)`""
}
else
{
Invoke-Expression "`$arg = [$($param.Type)]::Parse(`"$($param.Value)`")"
}
}
$arguments += $arg
}
}
if($arguments.Count -gt 0)
{
Write-Host "Adding arguments `"$argumentsNames`" for role $($roleConfig.roleName)"
}
if (!$rolePSSession)
{
$rolePSSession = $roleConfig.PSSession
}
}
else
{
if (!$arguments)
{
$arguments = @()
}
# check global parameters for invoked helpers
if ($xmlConfig.Configuration.GlobalParams)
{
$fileParams = $xmlConfig.Configuration.GlobalParams.Param | ?{$fileName -match $_.Helper}
foreach($fParam in $fileParams)
{
foreach($fparam in $fileParams)
{
if ($fparam.Type -match "string")
{
Invoke-Expression "`$filearg = [$($fparam.Type)]`"$($fparam.Value)`""
}
else
{
Invoke-Expression "`$filearg = [$($fparam.Type)]::Parse(`"$($fparam.Value)`")"
}
Write-Host "Adding argument `"$($fparam.Name)`" with value `"$filearg`" for helpers $fileName" -ForegroundColor Magenta
$arguments += $filearg
}
}
}
}
if ($rolePSSession)
{
$usePSSession = $true
foreach($param in $rolePSSession.Param)
{
if ($param.variable)
{
$varName = $param.variable
Invoke-Expression "`$paramValue = `$(`$param.value) -f $varName"
}
else
{
$paramValue = $param.value
}
$psSessionParams.Add($param.Name, $paramValue)
if ($param.Name -eq "ConfigurationName")
{
Write-Host "Using ps session configuration name `"$paramValue`"" -ForegroundColor Yellow
}
}
$arguments += $true
}
$status = 0
for($i = 1; $i -le $maxStepIterations -and $status -eq 0; $i++)
{
try
{
if ($i -gt 1) #
{
Log -Message "Waiting availability of '$serverName'..." -Color "Cyan"
do
{
Start-Sleep -Seconds 5
} while (!(Test-WSMan -ComputerName $serverName -ErrorAction SilentlyContinue))
Log -Message "'$serverName' is available" -Color "Cyan"
}
$invokeCommandParams = @{
FilePath = $fileName
ErrorAction = "Stop"
}
if ($usePSSession)
{
$session = New-PSSession @psSessionParams -Authentication Negotiate
$invokeCommandParams.Add("Session", $session)
#$arguments = $serverName
}
else
{
$invokeCommandParams.Add("ComputerName", $serverName)
}
$invokeCommandParams.Add("ArgumentList", $arguments)
if ($serverName -ne ".")
{
$stepResult = Invoke-Command @invokeCommandParams
}
else
{
$stepScriptBlock = Get-Command $fileName | select -ExpandProperty ScriptBlock
$stepResult = $stepScriptBlock.Invoke($arguments)
}
if ($stepResult -and $stepResult.Status -eq 0)
{
Log -Message $("Error `"{0}`" during step invoke on try $i of $maxStepIterations. Sleep 30 seconds" -f $($stepResult.Details)) -Color "Yellow"
Start-Sleep -Seconds 30
}
}
catch
{
Log -Message "Exception `"$_`" during step invoke on try $i of $maxStepIterations. Sleep 30 seconds" -Color "Red"
Start-Sleep -Seconds 30
$stepResult = New-Object PSCustomObject -Property @{
Status = 0;
Details = $_;
}
}
finally
{
if ($session -ne $null)
{
Remove-PSSession $session
}
}
if ($stepResult)
{
$status = $stepResult.Status
}
}
if (!([String]::IsNullOrEmpty($stepResult.Details)) -and !([String]::IsNullOrWhiteSpace($stepResult.Details)))
{
Log -Message $($stepResult.Details) -Server $serverName
}
if ($stepResult.Status -ne 1)
{
Log -Message $("Step failed! Status `"{1}`", Details: {0}" -f $($stepResult.Details), $stepResult.Status) -Color "Red" -Server $serverName
if ($DontStopOnError)
{
Log -Message "DontStopOnError switch defined. Continuing exectuion" -Color "Yellow"
$stepResult.Status = 1
}
}
$stepResult
}
function CheckFeaturesActions($featuresList, $prefix, $ServerName)
{
foreach($feature in $featuresList)
{
$scriptFileName = "$invokePath\$prefix\{0}.ps1" -f $feature
if (Test-Path $scriptFileName)
{
$computerName = $ServerName
$roleConfig = $xmlConfig.Configuration.Role | ? roleName -eq $feature
if ($roleConfig -ne $null -and $roleConfig.local -eq "true")
{
$computerName = "."
}
Log -Message $("Found $prefix-update script for feature '{0}'. Invoking on '$computerName'..." -f $feature) -Color "Yellow"
$actionsResult = InvokeStep -serverName $computerName -fileName $scriptFileName -arguments $ServerName -feature $feature
if ($actionsResult -eq $null -or $actionsResult.Status -eq 0)
{
Log -message "InvokeStep for feature $feature failed! Details: $($actionsResult.Details)"
return $false
}
}
}
return $true
}
function CheckPendingReboot
{
param($server, $features = $null, $forceReboot)
Log -Message "Check pending reboot for '$server'" -Color "Cyan"
$result = $(InvokeStep -serverName $server -fileName $pendingRebootStep)
if ($result.Status -eq 0)
{
return $false
}
if ($result.Data -or $forceReboot)
{
Log -Message "Reboot pending on '$server'. Rebooting..." -Color "Cyan"
if ($features)
{
Log -Message "Features list defined for '$server'. Invoking 'pre' steps..." -Color "Yellow"
if (!$(CheckFeaturesActions -featuresList $installedFeatures -prefix "pre" -ServerName $server))
{
throw $("CheckPendingReboot: pre steps failed!")
}
}
$rebootStart = Get-Date
try
{
Restart-Computer -ComputerName $server -Force -Wait -For Powershell -ErrorAction Stop
}
catch
{
Log -Message "'Restart-Computer' failed on '$server'. Invoke 'shutdown.exe'..." -Color "Cyan"
Invoke-Command -ComputerName $server -ScriptBlock { shutdown -r -t 0 }
Log -Message "Waiting for '$server' to shutdown..." -Color "Cyan"
while ($(Test-WSMan -ComputerName $server -ErrorAction SilentlyContinue)) {}
}
Log -Message "Waiting '$server' to startup and remoting is UP..." -Color "Cyan"
do
{
Start-Sleep -Seconds 5
} while (!(Test-WSMan -ComputerName $server -ErrorAction SilentlyContinue))
$rebootEnd = Get-Date
$rebootDiff = $rebootEnd - $rebootStart
Log -Message "'$server' is back after $($rebootDiff.TotalSeconds) sec" -Color "Cyan"
Log -Message "Starting services on '$server'" -Color "White"
$result = $(InvokeStep -serverName $server -fileName $startServicesStep) # Ignore results
if ($features)
{
Log -Message "Features list defined for '$server'. Invoking 'post' steps..." -Color "Yellow"
if (!$(CheckFeaturesActions -featuresList $installedFeatures -prefix "post" -ServerName $server))
{
throw ""
}
}
}
else
{
Log("Reboot not pending on '{0}'" -f $server) -Color "Cyan"
}
return $true
}
function SendReport
{
param([String]$Message = "...", [String]$Subject)
if ( !([String]::IsNullOrEmpty($SMTPServer)) -and !([String]::IsNullOrEmpty($SMTPFrom)) -and !([String]::IsNullOrEmpty($SMTPTo)))
{
$messageParameters = @{
Subject = $Subject
Body = $Message
From = $SMTPFrom
To = $SMTPTo
SmtpServer = $SMTPServer
}
Send-MailMessage @messageParameters
}
}
function Get-ADComputerViaADSI
{
param($name, $spn)
if (!([String]::IsNullOrEmpty($name)))
{
$nameParam = "(|(name=$name)(dnsHostName=$name))"
}
if (!([String]::IsNullOrEmpty($spn)))
{
$spnParam = "(ServicePrincipalName=$spn*)"
}
$domainDN = ([adsi]"LDAP://RootDSE").Properties["defaultNamingContext"]
$compSearcher = New-Object System.DirectoryServices.DirectorySearcher($domainDN)
$compSearcher.SearchScope = [System.DirectoryServices.SearchScope]::Subtree
$compSearcher.Filter = "(&(objectCategory=Computer)(!(userAccountControl:1.2.840.113556.1.4.803:=2)){0}{1})" -f $nameParam, $spnParam
[void]($compSearcher.PropertiesToLoad.Add("DNSHostName"))
$sortOption = New-Object System.DirectoryServices.SortOption("DNSHostName", [System.DirectoryServices.SortDirection]::Ascending);
$compSearcher.Sort = $sortOption
$resultComputers = $compSearcher.FindAll()
$resultComputers | %{ $_.Properties["DNSHostName"] }
}
#
# Main Body
#
try
{
if ($RebootServer)
{
$OnlyCheckReboot = $true
}
$updateProcessSuccess = $true
$localNetbios = $($env:ComputerName)
$localFQDN = "{0}.{1}" -f $($env:ComputerName), $((Get-WmiObject -Class Win32_ComputerSystem).Domain)
$invokePath = $(Split-Path $MyInvocation.MyCommand.Path)
$invokeDateTime = [DateTime]::now.Tostring("dd-MM-yyyy-HH-mm-ss")
if (! (Get-Item "$invokePath\Logs" -ErrorAction SilentlyContinue) )
{
[void](New-Item -ItemType Directory "$invokePath\Logs" -ErrorAction SilentlyContinue)
}
$logPattern = "$invokePath\Logs\{0}_$invokeDateTime.log"
$logFile = $logPattern -f "update"
$skippedLogFile = $logPattern -f "skipped"
$xmlConfigPath = "$invokePath\config.xml"
[xml]$xmlConfig = Get-Content $xmlConfigPath -ErrorAction SilentlyContinue
$installedFeaturesStep = "$invokePath\Helpers\Get-InstalledFeatures.ps1"
$pendingRebootStep = "$invokePath\Helpers\Pending-Reboot.ps1"
$installUpdatesStep = "$invokePath\Helpers\Install-Updates.ps1"
$startServicesStep = "$invokePath\Helpers\Start-Services.ps1"
$maxUpdateIterations = 6
$maxStepIterations = 5
if ($ServerList -ne $null)
{
$ServersForUpdate = @()
foreach($srv in $ServerList)
{
if ( !$($srv.Contains("*")) )
{
$ServersForUpdate += $srv
}
else
{
$maskedServersList = Get-ADComputerViaADSI -name $srv
foreach($maskSrv in $maskedServersList)
{
$ServersForUpdate += $maskSrv
}
}
}
}
elseif($ServerListFile)
{
$ServersForUpdate = (gc $ServerListFile).Split("`r`n", [System.StringSplitOptions]::RemoveEmptyEntries)
}
else
{
$ServersForUpdate = Get-ADComputerViaADSI
}
# send mail about start update process
$str = "Update process started at $invokeDateTime"
$message = "Updating servers: `r`n"
$message += $ServersForUpdate
Log -message $str
Log -message $($message | Out-String)
SendReport -Subject $str -Message $($message | Out-String)
if ($OnlyShowList)
{
$str = "OnlyShowList parameter speficied. Exiting"
Log -message $str
return
}
Log -message $("Invoked from '{0}'. Logging to '{1}'" -f $invokePath, $logFile)
$updatedServers = @()
$updatedCount = 0
foreach ($serverName in $ServersForUpdate)
{
$updatedCount++
$str = "Updating '{0}' ({1} of {2})" -f $serverName, $updatedCount, $ServersForUpdate.Count
Log -message $str -Color "Green"
SendReport -Subject $str
$skipped = $false
if ($SkipServers -ne $null)
{
$SkipServers | %{ if ($serverName -match $_) {
$mesStr = "'{0}' is in skipped list" -f $serverName
Log -message $mesStr -Color "Yellow"
SendReport -Subject $mesStr
$mesStr | Out-File $skippedLogFile -Append -Encoding ascii
$skipped = $true
}
}
}
if (!$skipped)
{
if ($serverName -eq $localNetbios -or $serverName -eq $localFQDN -or $SMTPServer -match $serverName)
{
$mesStr = "'{0}' is script execution server or SMTP server. Skipped" -f $serverName
Log -message $mesStr -Color "Yellow"
$mesStr | Out-File $skippedLogFile -Append -Encoding ascii
SendReport -Subject $mesStr
}
elseif ((Get-ADComputerViaADSI -name $serverName -spn "MSClusterVirtualServer").Count -gt 0)
{
$mesStr = "'{0}' is VCO or CNO. Skipped" -f $serverName
Log -message $mesStr -Color "Yellow"
$mesStr | Out-File $skippedLogFile -Append -Encoding ascii
SendReport -Subject $mesStr
}
else
{
if (!$(Test-WSMan -ComputerName $serverName -ErrorAction SilentlyContinue))
{
$mesStr = "'{0}' not responding. Skipped" -f $serverName
Log -message $mesStr -Color "Yellow"
$mesStr | Out-File $skippedLogFile -Append -Encoding ascii
SendReport -Subject $mesStr
}
else
{
$errorInUpdate = $false
$hasUpdates = $false
try
{
# get installed features for server
Log -Message $("Get installed features on '{0}'" -f $serverName) -Color "White"
$result = $(InvokeStep -serverName $serverName -fileName $installedFeaturesStep)
if ($result.Status -ne 1)
{
throw "Error invoke step `"$installedFeaturesStep`""
}
$installedFeatures = @($result.Data)
Log -Message $("Installed features: $installedFeatures") -Color "White"
# check skipped updates for roles
$skippedUpdates = @()
if ($xmlConfig -ne $null)
{
$rolesConfigrationList = $xmlConfig.Configuration.Role
if ($rolesConfigrationList -ne $null)
{
foreach($roleConfig in $rolesConfigrationList)
{
if ($installedFeatures -contains $roleConfig.roleName)
{
if (!$([String]::IsNullOrEmpty($roleConfig.skipUpdates)))
{
$skippedUpdates += $roleConfig.skipUpdates.Split(",", [System.StringSplitOptions]::RemoveEmptyEntries)
}
}
}
}
}
if (!$OnlyPostStep -and !$OnlyCheckReboot)
{
# check for updates on server
Log -Message $("Check for updates on '{0}'" -f $serverName) -Color "White"
$checkUpdatesResult = $(InvokeStep -serverName $serverName -fileName $installUpdatesStep -Arguments @($skippedUpdates, $true))
if ($checkUpdatesResult.Status -ne 1)
{
throw $("Error check for updates on '{0}'. Status {1}" -f $serverName, $($checkUpdatesResult.Status))
}
if ($([bool]::Parse($($checkUpdatesResult.Data))) -eq $true)
{
$hasUpdates = $true
$serverUpdated = $false
# check for pre-update step
if (!$(CheckFeaturesActions -featuresList $installedFeatures -prefix "pre" -ServerName $serverName))
{
throw "Check pre actions failed!"
}
<#
# TEMP for scvmm
if ($installedFeatures.Contains("VMMAgent"))
{
Log -Message $("Check for VMM agent update for '{0}'" -f $serverName) -Color "White"
$runasAccount = Get-SCRunAsAccount "Fabric Admin"
$managedComp = Get-SCVMMManagedComputer | ? name -match $serverName
Update-SCVMMManagedComputer -VMMManagedComputer $managedComp -Credential $runasAccount
} #>
#
# here update process
if (!$(CheckPendingReboot -server $serverName))
{
throw "Check pending reboot failed!"
}
$updateIterations = 0
while($serverUpdated -eq $false -and $updateIterations -le $maxUpdateIterations)
{
Log -Message $("Check and install updates on '{0}'" -f $serverName) -Color "White"
$result = $(InvokeStep -serverName $serverName -fileName $installUpdatesStep -Arguments @($skippedUpdates, $false))
if ($result.Status -ne 1)
{
if ($updateIterations -ne $maxUpdateIterations)
{
$updateIterations++
Log -Message $("Trying again after 30 seconds. Iteration '$updateIterations' of $maxUpdateIterations..." -f $serverName) -Color "White"
Start-Sleep -Seconds 30
}
else
{
throw "Maximum update iteration exceeded!"
}
}
else
{
$serverUpdated = $([bool]::Parse($($result.Data)))
}
# here check for reboot needed
if (!$(CheckPendingReboot -server $serverName))
{
throw "Check pending reboot failed!"
}
$updateIterations++
}
if ($updateIterations -eq $maxUpdateIterations)
{
$serverUpdated = $true
Log -Message $("Update process exceed max iterations($maxUpdateIterations). Possible WinUpdate loop" -f $serverName) -Color "Yellow"
}
# end of update process
#
if (!$serverUpdated)
{
throw "Not updated!"
}
}
else
{
$hasUpdates = $false
$noUpdatesMessage = $("No updates for '{0}'" -f $serverName)
Log -Message $noUpdatesMessage
SendReport -Subject $noUpdatesMessage
}
}
else
{
if (!$OnlyCheckReboot)
{
Log -Message "OnlyPostStep switch specified. Update skipped" -Color "Yellow"
}
} # only post step
if (!$OnlyCheckReboot)
{
if ($serverUpdated -or $OnlyPostStep)
{
# check for post-update step
if (!$(CheckFeaturesActions -featuresList $installedFeatures -prefix "post" -ServerName $serverName))
{
throw "Check post actions failed! $_"
}
}
elseif ($NoPostStep)
{
Log -Message "NoPostStep switch specified. Post step skipped" -Color "Yellow"
}
}
else
{
if ($RebootServer)
{
Log -Message "RebootServer switch specified. Force reboot" -Color "Yellow"
}
else
{
Log -Message "OnlyCheckReboot switch specified" -Color "Yellow"
}
if (!$(CheckPendingReboot -server $serverName -features $installedFeatures -forceReboot $RebootServer))
{
throw "Check pendiong reboot failed! $_"
}
}
}
catch
{
$errorInUpdate = $true
$serverUpdated = $false
Log -Message $("Exception in update script: '{0}'" -f $_) -Color "Red"
throw $_
}
finally
{
$serverUpdateReport = "..."
$serverLogPath = $($logPattern -f $serverName)
if ($(Test-Path $serverLogPath))
{
$serverUpdateReport = gc $serverLogPath -Raw
}
if ($hasUpdates -and $serverUpdated)
{
$updatedServers += $serverName
$updateStatus = "'{0}' updated successfully" -f $serverName
Log -Message $updateStatus -Color "White"
SendReport -Subject $updateStatus -Message $serverUpdateReport
}
elseif ($hasUpdates -and (!$serverUpdated -or $errorInUpdate))
{
$updateStatus = "'{0}' update failed" -f $serverName
Log -Message $updateStatus -Color "Red"
SendReport -Subject $updateStatus -Message $serverUpdateReport
throw ""
}
}
}
} # update
} # skipped
}
}
catch
{
$updateProcessSuccess = $false
Log -Message $("Exception in update script: '{0}'" -f $_) -Color "Red"
}
$str = "Update process finished at $([DateTime]::now.Tostring("dd-MM-yyyy-HH-mm-ss"))"
$updateReport = gc $logFile -Raw
if ($(Test-Path $skippedLogFile))
{
$skippedServers = (gc $skippedLogFile -Raw) | Out-String
}
$updatedServersString = $updatedServers | Out-String
$updateDetails = "Updated servers: $updatedServers`r`n`r`nSkipped servers: $skippedServers`r`n---------------"
Log -message $updateDetails
Log -message $str
SendReport -Subject $str -Message "$updateDetails`r`nUpdate log: `r`n$updateReport"