functions/Install-DbaFirstResponderKit.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
#ValidationTags#CodeStyle,Messaging,FlowControl,Pipeline#
function Install-DbaFirstResponderKit {
    <#
        .SYNOPSIS
            Installs or updates the First Responder Kit stored procedures.
 
        .DESCRIPTION
            Downloads, extracts and installs the First Responder Kit stored procedures:
            sp_Blitz, sp_BlitzWho, sp_BlitzFirst, sp_BlitzIndex, sp_BlitzCache and sp_BlitzTrace, etc.
 
            First Responder Kit links:
            http://FirstResponderKit.org
            https://github.com/BrentOzarULTD/SQL-Server-First-Responder-Kit
 
        .PARAMETER SqlInstance
            SQL Server name or SMO object representing the SQL Server to connect to.
 
        .PARAMETER SqlCredential
            Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)
 
        .PARAMETER Database
            Specifies the database to instal the First Responder Kit stored procedures into
 
        .PARAMETER Branch
            Specifies an alternate branch of the First Responder Kit to install. (master or dev)
 
        .PARAMETER Confirm
            Prompts to confirm actions
 
        .PARAMETER WhatIf
            Shows what would happen if the command were to run. No actions are actually performed.
 
        .PARAMETER EnableException
            By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
            This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
            Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.
 
        .NOTES
            Tags: BrentOzar, FRK, FirstResponderKit
            Author: Tara Kizer, Brent Ozar Unlimited (https://www.brentozar.com/)
            Website: https://dbatools.io
            Copyright: (C) Chrissy LeMaire, clemaire@gmail.com
            License: MIT https://opensource.org/licenses/MIT
 
        .LINK
            https://dbatools.io/Install-DbaFirstResponderKit
 
        .EXAMPLE
            Install-DbaFirstResponderKit -SqlInstance server1 -Database master
 
            Logs into server1 with Windows authentication and then installs the FRK in the master database.
 
        .EXAMPLE
            Install-DbaFirstResponderKit -SqlInstance server1\instance1 -Database DBA
 
            Logs into server1\instance1 with Windows authentication and then installs the FRK in the DBA database.
 
        .EXAMPLE
            Install-DbaFirstResponderKit -SqlInstance server1\instance1 -Database master -SqlCredential $cred
 
            Logs into server1\instance1 with SQL authentication and then installs the FRK in the master database.
 
        .EXAMPLE
            Install-DbaFirstResponderKit -SqlInstance sql2016\standardrtm, sql2016\sqlexpress, sql2014
 
            Logs into sql2016\standardrtm, sql2016\sqlexpress and sql2014 with Windows authentication and then installs the FRK in the master database.
 
        .EXAMPLE
            $servers = "sql2016\standardrtm", "sql2016\sqlexpress", "sql2014"
            $servers | Install-DbaFirstResponderKit
 
            Logs into sql2016\standardrtm, sql2016\sqlexpress and sql2014 with Windows authentication and then installs the FRK in the master database.
 
        .EXAMPLE
            Install-DbaFirstResponderKit -SqlInstance sql2016 -Branch dev
 
            Installs the dev branch version of the FRK in the master database on sql2016 instance.
    #>

    [CmdletBinding(SupportsShouldProcess = $true)]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [ValidateSet('master', 'dev')]
        [string]$Branch = "master",
        [object]$Database = "master",
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        $url = "https://codeload.github.com/BrentOzarULTD/SQL-Server-First-Responder-Kit/zip/$Branch"

        $temp = ([System.IO.Path]::GetTempPath()).TrimEnd("\")
        $zipfile = "$temp\SQL-Server-First-Responder-Kit-$Branch.zip"
        $zipfolder = "$temp\SQL-Server-First-Responder-Kit-$Branch\"

        if ($zipfile | Test-Path) {
            Remove-Item -Path $zipfile -ErrorAction SilentlyContinue
        }

        if ($zipfolder | Test-Path) {
            Remove-Item -Path $zipfolder -Recurse -ErrorAction SilentlyContinue
        }

        $null = New-Item -ItemType Directory -Path $zipfolder -ErrorAction SilentlyContinue

        Write-Message -Level Verbose -Message "Downloading and unzipping the First Responder Kit zip file."

        try {
            $oldSslSettings = [System.Net.ServicePointManager]::SecurityProtocol
            [System.Net.ServicePointManager]::SecurityProtocol = "Tls12"
            try {
                $wc = New-Object System.Net.WebClient
                $wc.DownloadFile($url, $zipfile)
            }
            catch {
                # Try with default proxy and usersettings
                $wc = New-Object System.Net.WebClient
                $wc.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
                $wc.DownloadFile($url, $zipfile)
            }
            [System.Net.ServicePointManager]::SecurityProtocol = $oldSslSettings

            # Unblock if there's a block
            Unblock-File $zipfile -ErrorAction SilentlyContinue

            Expand-Archive -Path $zipfile -DestinationPath $zipfolder -Force

            Remove-Item -Path $zipfile
        }
        catch {
            Stop-Function -Message "Couldn't download the First Responder Kit. Download and install manually from https://github.com/BrentOzarULTD/SQL-Server-First-Responder-Kit/archive/$Branch.zip." -ErrorRecord $_
            return
        }
    }

    process {
        if (Test-FunctionInterrupt) {
            return
        }

        foreach ($instance in $SqlInstance) {
            try {
                Write-Message -Level Verbose -Message "Connecting to $instance."
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            }
            catch {
                Stop-Function -Message "Failure." -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            Write-Message -Level Verbose -Message "Starting installing/updating the First Responder Kit stored procedures in $database on $instance."
            $allprocedures_query = "select name from sys.procedures where is_ms_shipped = 0"
            $allprocedures = ($server.Query($allprocedures_query, $Database)).Name
            # Install/Update each FRK stored procedure
            foreach ($script in (Get-ChildItem $zipfolder -Recurse -Filter "sp_*.sql")) {
                $scriptname = $script.Name
                $scriptError = $false
                if ($scriptname -ne "sp_BlitzRS.sql") {

                    if ($scriptname -eq "sp_BlitzQueryStore.sql") {
                        if ($server.VersionMajor -lt 13) { continue }
                    }
                    if ($Pscmdlet.ShouldProcess($instance, "installing/updating $scriptname in $database.")) {
                        try {
                            Invoke-DbaSqlQuery -SqlInstance $server -Database $Database -File $script.FullName -EnableException -Verbose:$false
                        } catch {
                            Write-Message -Level Warning -Message "Could not execute at least one portion of $scriptname in $Database on $instance." -ErrorRecord $_
                            $scriptError = $true
                        }
                        $baseres = @{
                            ComputerName = $server.ComputerName
                            InstanceName = $server.ServiceName
                            SqlInstance  = $server.DomainInstanceName
                            Database     = $Database
                            Name         = $script.BaseName
                        }
                        if ($scriptError) {
                            $baseres['Status'] = 'Error'
                        } elseif ($script.BaseName -in $allprocedures) {
                            $baseres['Status'] = 'Updated'
                        }
                        else {
                            $baseres['Status'] = 'Installed'
                        }
                        [PSCustomObject]$baseres
                    }
                }
            }
            Write-Message -Level Verbose -Message "Finished installing/updating the First Responder Kit stored procedures in $database on $instance."
        }
    }
}