function/Show-SQLServerUpdatesReport.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
#Requires -Version 4.0
function Show-SQLServerUpdatesReport {
    <#
.Synopsis
   Returns information about deficit of installed updates at instance SQL Server.
 
.DESCRIPTION
    This command download information about the newest available updates for instance SQL Server.
    Next, it checks build number instance SQL Server in organization (mandatory parameter) and it will return updates required for installation.
 
    Show-SQLServerUpdatesReport can return report in HTML format.
     
    This function use Get-SQLServerUpdates for download information about availability updates for all edition SQL Server.
    Function Get-SQ ServerUpdates is a part of the module SQLServerUpdateModule. More about its function in help.
 
.NOTES
    Author: Mateusz Nadobnik, mnadobnik.pl
    Requires: sysadmin access on SQL Servers
 
    SQLServerUpdates PowerShell module (http://mnadobnik.pl/sqlserverupdates, mnadobnik@gmail.com)
    Copyright (C) 2017 Mateusz Nadobnik
 
    .LINK
    http://mnadobnik.pl/sqlserverupdates
 
.EXAMPLE
    Show-SQLServerUpdates -Version '13.0.4422.0'
 
    Name :
    Product :
    VersionName : SQL Server 2014
    Edition :
    ProductLevel :
    Version : 12.0.4487.0
    Updates : {@{CumulativeUpdate=<a href="https://support.microsoft.com/en-us/help/4013098/cumulative-update-5-for-sq
                   l-server-2014-sp2">CU5</a>; ReleaseDate=2017/04/17; Build=12.0.5546; SupportEnds=2024/07/09; ServicePack
                   =}, @{CumulativeUpdate=<a href="https://support.microsoft.com/en-us/help/4010394/cumulative-update-4-for
                   -sql-server-2014-sp2">CU4</a>; ReleaseDate=2017/02/21; Build=12.0.5540; SupportEnds=2024/07/09; ServiceP
                   ack=}, @{CumulativeUpdate=<a href="https://support.microsoft.com/en-us/kb/3204388">CU3</a>; ReleaseDate=
                   2016/12/27; Build=12.0.5538; SupportEnds=2024/07/09; ServicePack=}, @{CumulativeUpdate=<a href="https://
                   support.microsoft.com/en-us/kb/3188778">CU2</a>; ReleaseDate=2016/10/18; Build=12.0.5522; SupportEnds=20
                   24/07/09; ServicePack=}...}
    ToUpdate : True
 
    Returns information about deficit of installed updates for version builid SQL Server.
 
 .EXAMPLE
    Show-SQLServerUpdates -Version '12.0.4502' | Select -Expand Updates
 
    CumulativeUpdate : <a href="https://support.microsoft.com/en-us/help/4013098/cumulative-update-5-for-sql-server-2014-sp
                       2">CU5</a>
    ReleaseDate : 2017/04/17
    Build : 12.0.5546
    SupportEnds : 2024/07/09
    ServicePack :
 
    CumulativeUpdate : <a href="https://support.microsoft.com/en-us/help/4010394/cumulative-update-4-for-sql-server-2014-sp
                       2">CU4</a>
    ReleaseDate : 2017/02/21
    Build : 12.0.5540
    SupportEnds : 2024/07/09
    ServicePack :
    ...
 
   Returns information about deficit of installed updates for build number SQL Server. Expand properties Updates.
 
.EXAMPLE
    Show-SQLServerUpdatesReport -ServerInstance it-mn-m\mssqlserver14, test-agsqlserver
 
    Name : it-mn-m\mssqlserver14
    Product : Microsoft SQL Server
    VersionName : SQL Server 2014
    Edition : Developer Edition (64-bit)
    ProductLevel : SP1
    Build : 12.0.4487.0
    Updates : {@{CumulativeUpdate=<a href="https://support.microsoft.com/en-us/help/4013098/cumulative-update-5-for-sq
                   l-server-2014-sp2">CU5</a>; ReleaseDate=2017/04/17; Build=12.0.5546; SupportEnds=2024/07/09; ServicePack
                   =}, @{CumulativeUpdate=<a href="https://support.microsoft.com/en-us/help/4010394/cumulative-update-4-for
                   -sql-server-2014-sp2">CU4</a>; ReleaseDate=2017/02/21; Build=12.0.5540; SupportEnds=2024/07/09; ServiceP
                   ack=}, @{CumulativeUpdate=<a href="https://support.microsoft.com/en-us/kb/3204388">CU3</a>; ReleaseDate=
                   2016/12/27; Build=12.0.5538; SupportEnds=2024/07/09; ServicePack=}, @{CumulativeUpdate=<a href="https://
                   support.microsoft.com/en-us/kb/3188778">CU2</a>; ReleaseDate=2016/10/18; Build=12.0.5522; SupportEnds=20
                   24/07/09; ServicePack=}...}
    ToUpdate : True
 
    Returns information about deficit of installed updates for instance with parameter ServerInstance. This command returns objects.
 
.EXAMPLE
    Show-SQLServerUpdatesReport -ServerInstance it-mn-m\mssqlserver14, test-agsqlserver -HTML -Path C:\temp\report.html
 
    Return information about deficit of installed updates for instances with parameter ServerInstance. This command returns report in the format html.
 
.LINK
   Author: Mateusz Nadobnik
   Link: mnadobnik.pl
   Date: 16.07.2017
   Version: 1.0.0.6
     
   Keywords: SQL Server, Updates, Get, Reports, Show
   Notes: 1.0.0.4 - Without change.
          1.0.0.6 - issue repaired - HTML Report Has Duplicates the previous Servers available builds
                    Repaired syntax and change changed name variables "$object" to $ObjAllSserversWithUpdates
          1.0.0.8 - fixed problem with parameters in a pipeline
          1.0.0.9 - added warning
 
#>


    [CmdletBinding()]
    [Alias()]
    [OutputType([string])]
    Param
    (
        #The SQL Server instance
        [Parameter(Mandatory = $true,
            ValueFromPipeline = $true,
            Position = 0,
            ParameterSetName = 'Instance')]
        [Alias('SqlInstance')]
        $ServerInstance,
        #Build number SQL Server, example 13.0.4422.0
        [Parameter(Mandatory = $true,
            ValueFromPipelineByPropertyName = $true, 
            Position = 1, 
            ParameterSetName = 'Version')]
        [string]$BuildNumber,
        #Return report HTML
        [switch]$HTML
    )
    DynamicParam {
        if ($HTML) {
            #create a new ParameterAttribute Object
            $pathAttribute = New-Object System.Management.Automation.ParameterAttribute
            $pathAttribute.Mandatory = $true
 
            #create an attributecollection object for the attribute we just created.
            $attributeCollection = new-object System.Collections.ObjectModel.Collection[System.Attribute]
 
            #add our custom attribute
            $attributeCollection.Add($pathAttribute)
 
            #add our paramater specifying the attribute collection
            $pathParam = New-Object System.Management.Automation.RuntimeDefinedParameter('Path', [string], $attributeCollection)
 
            #expose the name of our parameter
            $paramDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
            $paramDictionary.Add('Path', $pathParam)
            return $paramDictionary
        }
    }
    Begin {
        Write-Warning "[Show-SQLServerUpdatesReport] Using the function Show-SQLServerUpdatesReport is deprecated. This function will be removed in version 2.0.0.0 or before, use Invoke-SqlServerUpdatesScan and Export-SqlServerUpdatesScan instead." -Verbose
        Write-Warning "[Show-SQLServerUpdatesReport] For example: Invoke-SqlServerUpdatesScan -ServerInstance IT-MN-M | Export-SqlServerUpdatesScan -File C:\report-updates.html"
        #Variables
        [array]$ObjAllSserversWithUpdates = @()

        #Check path to file with report
        if ($HTML) {
            #Check path
            if ($PSBoundParameters.Path -notmatch '[.]html') {
                Write-Host "The path $($PSBoundParameters.Path) not contain file with extension html"
                break
            }

            if (-not (Test-Path (Split-Path -Path $PSBoundParameters.Path))) {
                Write-Host "Not correct path. The directory $(Split-Path -Path $PSBoundParameters.Path) not exist."
                break
            }
        }
        
        if ($BuildNumber) {
            #Create new object
            $ServerInstance = @{ } | Select-Object VersionMajor, Build, VersionName
            $ServerInstance.Build = $BuildNumber
            $ServerInstance.VersionName = Get-SQLServerFullName ([int]($BuildNumber.Split(".")[0]))
            #$ServerInstance.VersionName = Get-SQLServerVersion ([int]($BuildNumber.Split(".")[0]))
            $ServerInstance.VersionMajor = [int]($BuildNumber.Split(".")[0])

            try {
                Write-Verbose "Get update list for $($ServerInstance.VersionName)" 
                $UpdateList = Get-SQLServerUpdates -Version $ServerInstance.VersionName
            }
            catch {
                Write-Host $_.Exception.Message
                exit 1
            }
        }
        else {
            try {
                Write-Verbose "Get update list for all SQL Server"
                $UpdateList = Get-SQLServerUpdates
            }
            catch {
                Write-Warning $_.Exception.Message
                exit 1
            }
        }
    }

    Process {
        foreach ($SqlInstance in $ServerInstance) {

            #Clear variables
            $ObjServer = @()
            $ObjUpdates = @()

            if (-not $BuildNumber) {  
                Write-Debug "[if (-not $BuildNumber)]:true"
                Write-Verbose "Run:Get-SQLServerVersion, Parameters :-ServerInstance $SqlInstance"
                $Instance = Get-SQLServerVersion -ServerInstance $SqlInstance
                Write-Verbose "Result:Get-SQLServerVersion $Instance"
            }
            else {
                Write-Debug "[if (-not $BuildNumber)]:false"
                Write-Verbose "$SqlInstance"
                $Instance = $SqlInstance
            }

            if ([int]($Instance.VersionMajor) -le 8) {
                Write-Debug "[if ($($Instance.VersionMajor) -le 8)]:true" 
                Write-Warning "Problem with connect or checked you server with SQL Server 2005 and earlier version"
            }

            #Create new object
            $ObjServer = @{ } | Select-Object Name, Product, VersionName, Edition, ProductLevel, Build, Updates, ToUpdate
            $ObjServer.Name = $Instance.Name
            $ObjServer.Product = $Instance.Product
            $ObjServer.VersionName = $Instance.VersionName
            $ObjServer.Edition = $Instance.Edition
            $ObjServer.ProductLevel = $Instance.ProductLevel
            $ObjServer.Build = $Instance.Build    

            # If check updates for SQL Server 2005
            if ([int]($Instance.VersionMajor) -eq 9) {
                Write-Debug "[[int]($($Instance.VersionMajor)) -eq 9]:true" 

                $ObjUpdate = @{ } | Select-Object CumulativeUpdate, ReleaseDate, Build, SupportEnds, ServicePack
                $ObjUpdate.CumulativeUpdate = ""
                $ObjUpdate.ReleaseDate = "2012/10/09"
                $ObjUpdate.Build = "9.00.5324"
                $ObjUpdate.SupportEnds = "2016/04/12 – out of support"
                $ObjUpdate.ServicePack = ""

                $ObjServer.Updates = $ObjUpdate
                $ObjServer.ToUpdate = $true
            }

            if ([int]($Instance.VersionMajor) -ge 9) {
                Write-Debug "[[int]($($Instance.VersionMajor)) -ge 9]:true" 
                $UpdatesServer = $UpdateList | Where-Object Name -eq $Instance.VersionName    
                
                # if SQL Server is latest Version
                if (([double](($Instance.Build) -Replace "\.(.|..)\.", "") -ge [double](($UpdatesServer[0].Build) -replace "\.(.|..)\.", "")) -or ($UpdatesServer[0].Build -eq "") -and ($UpdatesServer[0].Build -ne "various")) {
                    Write-Debug "[([double](($($Instance.Build)) -Replace '\.(.|..)\.', '') -ge [double](($($UpdatesServer[0].Build)) -replace '\.(.|..)\.', ''))]:true"
                    $ObjUpdate = @{ } | Select-Object CumulativeUpdate, ReleaseDate, Build, SupportEnds, ServicePack
                    $ObjUpdate.CumulativeUpdate = $UpdatesServer[0].CumulativeUpdate
                    $ObjUpdate.ReleaseDate = $UpdatesServer[0].ReleaseDate
                    $ObjUpdate.Build = $UpdatesServer[0].Build
                    $ObjUpdate.SupportEnds = $UpdatesServer[0].SupportEnds
                    $ObjUpdate.ServicePack = $UpdatesServer[0].ServicePack 

                    $ObjServer.Updates = $ObjUpdate
                    if (([double](($Instance.Build) -Replace "\.(.|..)\.", "") -ge [double](($UpdatesServer[0].Build) -replace "\.(.|..)\.", ""))) {
                        Write-Debug "[if (([double](($Instance.Build) -Replace '\.(.|..)\.', '') -ge [double](($($UpdatesServer[0].Build)) -replace '\.(.|..)\', '')))]:true"
                        Write-Verbose "Setting property: ToUpdate = false"
                        $ObjServer.ToUpdate = $false
                    }
                    else {
                        Write-Verbose "Setting property: ToUpdate = true"
                        $ObjServer.ToUpdate = $true
                    }
                }
                else {
                    #Issue - HTML Report Has Duplicates the previous Servers available builds
                    foreach ($Update in $UpdatesServer) {
                        if ($Update.Build -ne "various") {
                            Write-Debug "[if ($($Update.Build) -ne 'various')]:true"
                            if ([double](($Instance.Build) -Replace "\.(.|..)\.", "") -lt [double](($Update.Build) -replace "\.(.|..)\.", "")) {
                                Write-Debug "[if ([double](($($Instance.Build)) -Replace '\.(.|..)\.', '') -lt [double](($($Update.Build)) -replace '\.(.|..)\.', ''))]:true"
                                $ObjUpdate = @{ } | Select-Object CumulativeUpdate, ReleaseDate, Build, SupportEnds, ServicePack
                                $ObjUpdate.CumulativeUpdate = $Update.CumulativeUpdate
                                $ObjUpdate.ReleaseDate = $Update.ReleaseDate
                                $ObjUpdate.Build = $Update.Build
                                $ObjUpdate.SupportEnds = $Update.SupportEnds
                                $ObjUpdate.ServicePack = $Update.ServicePack 

                                # Save not installed update
                                $ObjUpdates += $ObjUpdate
                            }
                        }
                    }

                    $ObjServer.Updates = $ObjUpdates
                    $ObjServer.ToUpdate = $true
                }
                # Add to array
                $ObjAllSserversWithUpdates += $ObjServer
            }
        }
    }
    End {
        [string]$MessageBody = $null
        # Style CSS
        [string]$StyleCSS = "<style>
                            body
                            {
                                font-family:Calibri;
                                font-size:12pt;
                                background: #fafafa;
                                color: #5a5a5a;
                            }
                            h1
                            {
                                font-size: 38px;
                                line-height: 48px;
                                font-weight: 100;
                            }
                            td.toupdate
                            {
                                color:#e10707;
                                font-weight: 700;
                            }
                            tr:nth-child(odd) td, tr:nth-child(odd) th
                            {
                                background-color: #f8f8f8;
                            }
                            td
                            {
                                padding: 8px;
                                line-height: 18px;
                                text-align: center;
                                vertical-align: top;
                                border-top: 1px solid #dddddd;
                            }
                            table td
                            {
                                padding: 8px;
                                line-height: 18px;
                                text-align: center;
                                vertical-align: top;
                                border-top: 1px solid #dddddd;
                            }
 
                            table
                            {
                                border-bottom: 5px solid rgba(225,7,7,.5);
                                border-collapse: collapse;
                                border-spacing: 0;
                                font-size: 14px;
                                line-height: 2;
                                margin: 0 0 20px;
                                width: 100%;
                            }
                            a
                            {
                                color: #e10707;
                                text-decoration:none;
                            }
                            a:hover
                            {
                                 text-decoration:underline;
                                 color:#FF0000;
                            }
                            body
                            {
                                font-family:Calibri;
                                font-size:12pt;
                                background: #fafafa;
                                color: #5a5a5a;
                            }
                            h1
                            {
                                font-size: 38px;
                                line-height: 48px;
                                font-weight: 100;
                            }
                            td.toupdate
                            {
                                color:#e10707;
                                font-weight: 700;
                            }
                            tr:nth-child(odd) td, tr:nth-child(odd) th
                            {
                                background-color: #f8f8f8;
                            }
                            td
                            {
                                padding: 8px;
                                line-height: 18px;
                                text-align: center;
                                vertical-align: top;
                                border-top: 1px solid #dddddd;
                            }
                            table td
                            {
                                padding: 8px;
                                line-height: 18px;
                                text-align: center;
                                vertical-align: top;
                                border-top: 1px solid #dddddd;
                            }
 
                            table
                            {
                                border-bottom: 5px solid rgba(225,7,7,.5);
                                border-collapse: collapse;
                                border-spacing: 0;
                                font-size: 14px;
                                line-height: 2;
                                margin: 0 0 20px;
                                width: 100%;
                            }
                            a
                            {
                                color: #e10707;
                                text-decoration:none;
                            }
                            a:hover
                            {
                                    text-decoration:underline;
                                    color:#FF0000;
                            }
                                                        </style>"

        $MessageBody += $StyleCSS

        $PostContent = "Author <a href='http://mnadobnik.pl/SQLServerUpdatesModule' target='_blank'>SQLServerUpdatesModule</a> - Mateusz Nadobnik</br>
                        Information about updates getting with site <a href='https://sqlserverupdates.com' target='_blank'>https://sqlserverupdates.com</a>"


        #Header for report
        if ($ObjAllSserversWithUpdates.Name) {
            $HeaderReport = ($ObjAllSserversWithUpdates.Name).ToUpper() -join ', '
        }
        elseif ($BuildNumber) {
            $HeaderReport = $BuildNumber
        }

        #Prepare HTML
        if ($HTML -and $ObjAllSserversWithUpdates) {
            Write-Verbose "Preparation of an HTML report"
            Write-Debug "[($HTML -and $ObjAllSserversWithUpdates)]:true"
            $MessageBody += "<h1>Updates Report - ($HeaderReport)</h1></br></br>"
            $MessageBody += (((($ObjAllSserversWithUpdates | Select-Object ToUpdate, @{L = "Name"; E = { ($_.Name).ToUpper() } }, Product, VersionName, Edition, ProductLevel, `
                            @{L = "Current Build"; E = { $_.Build } }, `
                            @{L = "Available Build"; E = { (($_.Updates).Build) -join " </br> " } }, `
                            @{L = "Cumulative Update"; E = { (($_.Updates).CumulativeUpdate) -join " </br> " } }, `
                            @{L = "Release Date"; E = { (($_.Updates).ReleaseDate) -join " </br> " } }, `
                            @{L = "Support Ends"; E = { "<b>$((($_.Updates).SupportEnds)-join " </br> ")</b>" } }, `
                            @{L = "ServicePack "; E = { (($_.Updates).ServicePack) -join "</br> " } } |
                            ConvertTo-Html -Title "Updates Report" -PostContent $PostContent).Replace("&lt;", "<")).Replace("&gt;", ">")).Replace("&quot;", """")).replace("<tr><td>True", "<tr><td class='toupdate'>True") 
            try {
                Write-Verbose "Create file: $($PSBoundParameters.Path)"
                $MessageBody | Out-File $PSBoundParameters.Path
            }
            catch {
                Write-Warning $_.Exception.Message
            }
        }
        else {
            return $ObjAllSserversWithUpdates
        }
    }
}