functions/Install-DbaSqlWatch.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
#ValidationTags#CodeStyle,Messaging,FlowControl,Pipeline#
function Install-DbaSqlWatch {
    <#
    .SYNOPSIS
        Installs or updates SqlWatch.
 
    .DESCRIPTION
        Downloads, extracts and installs or updates SqlWatch.
        https://sqlwatch.io/
 
    .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 install SqlWatch into. Defaults to SQLWATCH.
 
    .PARAMETER LocalFile
        Specifies the path to a local file to install SqlWatch from. This *should* be the zipfile as distributed by the maintainers.
        If this parameter is not specified, the latest version will be downloaded and installed from https://github.com/marcingminski/sqlwatch
 
    .PARAMETER Force
        If this switch is enabled, SqlWatch will be downloaded from the internet even if previously cached.
 
    .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: SqlWatch
        Author: Ken K (github.com/koglerk)
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT
 
    .LINK
        https://dbatools.io/Install-DbaSqlWatch
 
    .EXAMPLE
        Install-DbaSqlWatch -SqlInstance server1
 
        Logs into server1 with Windows authentication and then installs SqlWatch in the SQLWATCH database.
 
    .EXAMPLE
        Install-DbaSqlWatch -SqlInstance server1\instance1 -Database DBA
 
        Logs into server1\instance1 with Windows authentication and then installs SqlWatch in the DBA database.
 
    .EXAMPLE
        Install-DbaSqlWatch -SqlInstance server1\instance1 -Database DBA -SqlCredential $cred
 
        Logs into server1\instance1 with SQL authentication and then installs SqlWatch in the DBA database.
 
    .EXAMPLE
        Install-DbaSqlWatch -SqlInstance sql2016\standardrtm, sql2016\sqlexpress, sql2014
 
        Logs into sql2016\standardrtm, sql2016\sqlexpress and sql2014 with Windows authentication and then installs SqlWatch in the SQLWATCH database.
 
    .EXAMPLE
        $servers = "sql2016\standardrtm", "sql2016\sqlexpress", "sql2014"
        $servers | Install-DbaSqlWatch
 
        Logs into sql2016\standardrtm, sql2016\sqlexpress and sql2014 with Windows authentication and then installs SqlWatch in the SQLWATCH database.
    #>

    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = "Low")]
    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string]$Database = "SQLWATCH",
        [string]$LocalFile,
        [switch]$Force,
        [switch]$EnableException
    )
    begin {
        $stepCounter = 0

        $DbatoolsData = Get-DbatoolsConfigValue -FullName "Path.DbatoolsData"
        $tempFolder = ([System.IO.Path]::GetTempPath()).TrimEnd("\")
        $zipfile = "$tempFolder\SqlWatch.zip"

        if (-not $LocalFile) {
            if ($PSCmdlet.ShouldProcess($env:computername, "Downloading latest release from GitHub")) {
                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Downloading latest release from GitHub"
                # query the releases to find the latest, check and see if its cached
                $ReleasesUrl = "https://api.github.com/repos/marcingminski/sqlwatch/releases"
                $DownloadBase = "https://github.com/marcingminski/sqlwatch/releases/download/"

                Write-Message -Level Verbose -Message "Checking GitHub for the latest release."
                $LatestReleaseUrl = (Invoke-TlsWebRequest -UseBasicParsing -Uri $ReleasesUrl | ConvertFrom-Json)[0].assets[0].browser_download_url

                Write-Message -Level VeryVerbose -Message "Latest release is available at $LatestReleaseUrl"
                $LocallyCachedZip = Join-Path -Path $DbatoolsData -ChildPath $($LatestReleaseUrl -replace $DownloadBase, '');

                # if local cached copy exists, use it, otherwise download a new one
                if (-not $Force) {

                    # download from github
                    Write-Message -Level Verbose "Downloading $LatestReleaseUrl"
                    try {
                        Invoke-TlsWebRequest $LatestReleaseUrl -OutFile $zipfile -ErrorAction Stop -UseBasicParsing
                    } catch {
                        #try with default proxy and usersettings
                        (New-Object System.Net.WebClient).Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
                        Invoke-TlsWebRequest $LatestReleaseUrl -OutFile $zipfile -ErrorAction Stop -UseBasicParsing
                    }

                    # copy the file from temp to local cache
                    Write-Message -Level Verbose "Copying $zipfile to $LocallyCachedZip"
                    try {
                        New-Item -Path $LocallyCachedZip -ItemType File -Force | Out-Null
                        Copy-Item -Path $zipfile -Destination $LocallyCachedZip -Force
                    } catch {
                        # should we stop the function if the file copy fails?
                        # here to avoid an empty catch
                        $null = 1
                    }
                }
            }
        } else {

            # $LocalFile was passed, so use it
            if ($PSCmdlet.ShouldProcess($env:computername, "Copying local file to temp directory")) {

                if ($LocalFile.EndsWith("zip")) {
                    $LocallyCachedZip = $zipfile
                    Copy-Item -Path $LocalFile -Destination $LocallyCachedZip -Force
                } else {
                    $LocallyCachedZip = (Join-Path -path $tempFolder -childpath "SqlWatch.zip")
                    Copy-Item -Path $LocalFile -Destination $LocallyCachedZip -Force
                }
            }
        }

        # expand the zip file
        if ($PSCmdlet.ShouldProcess($env:computername, "Unpacking zipfile")) {
            Write-Message -Level VeryVerbose "Unblocking $LocallyCachedZip"
            Unblock-File $LocallyCachedZip -ErrorAction SilentlyContinue
            $LocalCacheFolder = Split-Path $LocallyCachedZip -Parent

            Write-Message -Level Verbose "Extracting $LocallyCachedZip to $LocalCacheFolder"
            if (Get-Command -ErrorAction SilentlyContinue -Name "Expand-Archive") {
                try {
                    Expand-Archive -Path $LocallyCachedZip -DestinationPath $LocalCacheFolder -Force
                } catch {
                    Stop-Function -Message "Unable to extract $LocallyCachedZip. Archive may not be valid." -ErrorRecord $_
                    return
                }
            } else {
                # Keep it backwards compatible
                $shell = New-Object -ComObject Shell.Application
                $zipPackage = $shell.NameSpace($LocallyCachedZip)
                $destinationFolder = $shell.NameSpace($LocalCacheFolder)
                Get-ChildItem "$LocalCacheFolder\SqlWatch.zip" | Remove-Item
                $destinationFolder.CopyHere($zipPackage.Items())
            }

            Write-Message -Level VeryVerbose "Deleting $LocallyCachedZip"
            Remove-Item -Path $LocallyCachedZip
        }
    }
    process {
        if (Test-FunctionInterrupt) {
            return
        }

        foreach ($instance in $SqlInstance) {
            if ($PSCmdlet.ShouldProcess($instance, "Installing SqlWatch on $Database")) {
                try {
                    $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
                } catch {
                    Stop-Function -Message "Failure." -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
                }

                Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Starting installing/updating SqlWatch in $database on $instance"


                try {
                    # create a publish profile and publish DACPAC
                    $DacPacPath = Get-ChildItem -Filter "SqlWatch.dacpac" -Path $LocalCacheFolder -Recurse | Select-Object -ExpandProperty FullName
                    $PublishOptions = @{
                        RegisterDataTierApplication = $true
                    }

                    Write-ProgressHelper -StepNumber ($stepCounter++) -Message "Publishing SqlWatch dacpac to $database on $instance"
                    $DacProfile = New-DbaDacProfile -SqlInstance $server -Database $Database -Path $LocalCacheFolder -PublishOptions $PublishOptions | Select-Object -ExpandProperty FileName
                    $PublishResults = Publish-DbaDacPackage -SqlInstance $server -Database $Database -Path $DacPacPath -PublishXml $DacProfile

                    # parse results
                    $parens = Select-String -InputObject $PublishResults.Result -Pattern "\(([^\)]+)\)" -AllMatches
                    if ($parens.matches) {
                        $ExtractedResult = $parens.matches | Select-Object -Last 1
                    }

                    [PSCustomObject]@{
                        ComputerName = $PublishResults.ComputerName
                        InstanceName = $PublishResults.InstanceName
                        SqlInstance  = $PublishResults.SqlInstance
                        Database     = $PublishResults.Database
                        Status       = $ExtractedResult
                    }
                } catch {
                    Stop-Function -Message "DACPAC failed to publish to $database on $instance." -ErrorRecord $_ -Target $instance -Continue
                }

                Write-Message -Level Verbose -Message "Finished installing/updating SqlWatch in $database on $instance."
            }
        }
    }
}