functions/Set-DbaMaxDop.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
function Set-DbaMaxDop {
    <#
        .SYNOPSIS
            Sets SQL Server maximum degree of parallelism (Max DOP), then displays information relating to SQL Server Max DOP configuration settings. Works on SQL Server 2005 and higher.
 
        .DESCRIPTION
            Uses the Test-DbaMaxDop command to get the recommended value if -MaxDop parameter is not specified.
 
            These are just general recommendations for SQL Server and are a good starting point for setting the "max degree of parallelism" option.
 
            You can set MaxDop database scoped configurations if the server is version 2016 or higher
 
        .PARAMETER SqlInstance
            The SQL Server instance 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 one or more databases to process. Options for this list are auto-populated from the server. If unspecified, all databases will be processed.
 
        .PARAMETER ExcludeDatabase
            Specifies one or more databases to exclude from processing. Options for this list are auto-populated from the server
 
        .PARAMETER MaxDop
            Specifies the Max DOP value to set.
 
        .PARAMETER AllDatabases
            If this switch is enabled, Max DOP will be set on all databases. This switch is only useful on SQL Server 2016 and higher.
 
        .PARAMETER Collection
            If Test-SQLMaxDop has been executed prior to this function, the results may be passed in via this parameter.
 
        .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.
 
        .PARAMETER WhatIf
            Shows what would happen if the cmdlet runs. The cmdlet is not run.
 
        .PARAMETER Confirm
            Prompts you for confirmation before running the cmdlet.
 
        .NOTES
            Tags: MaxDop, SpConfigure
            Author: Claudio Silva (@claudioessilva)
 
            Website: https://dbatools.io
            Copyright: (C) Chrissy LeMaire, clemaire@gmail.com
            License: MIT https://opensource.org/licenses/MIT
 
        .LINK
            https://dbatools.io/Set-DbaMaxDop
 
        .EXAMPLE
            Set-DbaMaxDop -SqlInstance sql2008, sql2012
 
            Sets Max DOP to the recommended value for servers sql2008 and sql2012.
 
        .EXAMPLE
            Set-DbaMaxDop -SqlInstance sql2014 -MaxDop 4
 
            Sets Max DOP to 4 for server sql2014.
 
        .EXAMPLE
            Test-DbaMaxDop -SqlInstance sql2008 | Set-DbaMaxDop
 
            Gets the recommended Max DOP from Test-DbaMaxDop and applies it to to sql2008.
 
        .EXAMPLE
            Set-DbaMaxDop -SqlInstance sql2016 -Database db1
 
            Set recommended Max DOP for database db1 on server sql2016.
 
        .EXAMPLE
            Set-DbaMaxDop -SqlInstance sql2016 -AllDatabases
 
            Set recommended Max DOP for all databases on server sql2016.
 
    #>

    [CmdletBinding(SupportsShouldProcess = $true)]
    param (
        [parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $True)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]$SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [int]$MaxDop = -1,
        [Parameter(ValueFromPipeline = $True)]
        [object]$Collection,
        [Alias("All")]
        [switch]$AllDatabases,
        [Alias('Silent')]
        [switch]$EnableException
    )

    begin {
        $processed = New-Object System.Collections.ArrayList
        $results = @()
    }
    process {
        if ((Test-Bound -Parameter Database) -and (Test-Bound -Parameter AllDatabases) -and (Test-Bound -Parameter ExcludeDatabase)) {
            Stop-Function -Category InvalidArgument -Message "-Database, -AllDatabases and -ExcludeDatabase are mutually exclusive. Please choose only one. Quitting."
            return
        }

        $dbscopedconfiguration = $false

        if ($MaxDop -eq -1) {
            $UseRecommended = $true
        }

        if ((Test-Bound -Not -Parameter Collection)) {
            $collection = Test-DbaMaxDop -SqlInstance $sqlinstance -SqlCredential $SqlCredential -Verbose:$false
        }
        elseif ($null -eq $collection.SqlInstance) {
            $collection = Test-DbaMaxDop -SqlInstance $sqlinstance -SqlCredential $SqlCredential -Verbose:$false
        }

        $collection | Add-Member -Force -NotePropertyName OldInstanceMaxDopValue -NotePropertyValue 0
        $collection | Add-Member -Force -NotePropertyName OldDatabaseMaxDopValue -NotePropertyValue 0

        #If we have servers 2016 or higher we will have a row per database plus the instance level, getting unique we only run one time per instance
        $servers = $collection | Select-Object SqlInstance -Unique

        foreach ($server in $servers) {
            $servername = $server.SqlInstance

            Write-Message -Level Verbose -Message "Connecting to $servername"
            try {
                $server = Connect-SqlInstance -SqlInstance $servername -SqlCredential $SqlCredential
            }
            catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $servername -Continue
            }

            if (!(Test-SqlSa -SqlInstance $server)) {
                Stop-Function -Message "Not a sysadmin on $server. Skipping." -Category PermissionDenied -ErrorRecord $_ -Target $currentServer -Continue
            }

            if ($server.versionMajor -ge 13) {
                Write-Message -Level Verbose -Message "Server '$servername' supports Max DOP configuration per database."

                if ((Test-Bound -Not -Parameter Database) -and (Test-Bound -Not -Parameter ExcludeDatabase)) {
                    #Set at instance level
                    $collection = $collection | Where-Object { $_.DatabaseMaxDop -eq "N/A" }
                }
                else {
                    $dbscopedconfiguration = $true

                    if ((Test-Bound -Not -Parameter AllDatabases) -and (Test-Bound -Parameter Database)) {
                        $collection = $collection | Where-Object { $_.Database -in $Database }
                    }
                    elseif ((Test-Bound -Not -Parameter AllDatabases) -and (Test-Bound -Parameter ExcludeDatabase)) {
                        $collection = $collection | Where-Object { $_.Database -notin $ExcludeDatabase }
                    }
                    else {
                        if (Test-Bound -Parameter AllDatabases) {
                            $collection = $collection | Where-Object { $_.DatabaseMaxDop -ne "N/A" }
                        }
                        else {
                            $collection = $collection | Where-Object { $_.DatabaseMaxDop -eq "N/A" }
                            $dbscopedconfiguration = $false
                        }
                    }
                }
            }
            else {
                if ((Test-Bound -Parameter database) -or (Test-Bound -Parameter AllDatabases)) {
                    Write-Message -Level Warning -Message "Server '$servername' (v$($server.versionMajor)) does not support Max DOP configuration at the database level. Remember that this option is only available from SQL Server 2016 (v13). Run the command again without using database related parameters. Skipping."
                    Continue
                }
            }

            foreach ($row in $collection | Where-Object { $_.SqlInstance -eq $servername }) {
                if ($UseRecommended -and ($row.RecommendedMaxDop -eq $row.CurrentInstanceMaxDop) -and !($dbscopedconfiguration)) {
                    Write-Message -Level Verbose -Message "$servername is configured properly. No change required."
                    Continue
                }

                if ($UseRecommended -and ($row.RecommendedMaxDop -eq $row.DatabaseMaxDop) -and $dbscopedconfiguration) {
                    Write-Message -Level Verbose -Message "Database $($row.Database) on $servername is configured properly. No change required."
                    Continue
                }

                $row.OldInstanceMaxDopValue = $row.CurrentInstanceMaxDop

                try {
                    if ($UseRecommended) {
                        if ($dbscopedconfiguration) {
                            $row.OldDatabaseMaxDopValue = $row.DatabaseMaxDop

                            if ($resetDatabases) {
                                Write-Message -Level Verbose -Message "Changing $($row.Database) database max DOP to $($row.DatabaseMaxDop)."
                                $server.Databases["$($row.Database)"].MaxDop = $row.DatabaseMaxDop
                            }
                            else {
                                Write-Message -Level Verbose -Message "Changing $($row.Database) database max DOP from $($row.DatabaseMaxDop) to $($row.RecommendedMaxDop)."
                                $server.Databases["$($row.Database)"].MaxDop = $row.RecommendedMaxDop
                                $row.DatabaseMaxDop = $row.RecommendedMaxDop
                            }

                        }
                        else {
                            Write-Message -Level Verbose -Message "Changing $server SQL Server max DOP from $($row.CurrentInstanceMaxDop) to $($row.RecommendedMaxDop)."
                            $server.Configuration.MaxDegreeOfParallelism.ConfigValue = $row.RecommendedMaxDop
                            $row.CurrentInstanceMaxDop = $row.RecommendedMaxDop
                        }
                    }
                    else {
                        if ($dbscopedconfiguration) {
                            $row.OldDatabaseMaxDopValue = $row.DatabaseMaxDop

                            Write-Message -Level Verbose -Message "Changing $($row.Database) database max DOP from $($row.DatabaseMaxDop) to $MaxDop."
                            $server.Databases["$($row.Database)"].MaxDop = $MaxDop
                            $row.DatabaseMaxDop = $MaxDop
                        }
                        else {
                            Write-Message -Level Verbose -Message "Changing $servername SQL Server max DOP from $($row.CurrentInstanceMaxDop) to $MaxDop."
                            $server.Configuration.MaxDegreeOfParallelism.ConfigValue = $MaxDop
                            $row.CurrentInstanceMaxDop = $MaxDop
                        }
                    }

                    if ($dbscopedconfiguration) {
                        if ($Pscmdlet.ShouldProcess($row.Database, "Setting max dop on database")) {
                            $server.Databases["$($row.Database)"].Alter()
                        }
                    }
                    else {
                        if ($Pscmdlet.ShouldProcess($servername, "Setting max dop on instance")) {
                            $server.Configuration.Alter()
                        }
                    }

                    $results += [pscustomobject]@{
                        ComputerName           = $server.ComputerName
                        InstanceName           = $server.ServiceName
                        SqlInstance            = $server.DomainInstanceName
                        InstanceVersion        = $row.InstanceVersion
                        Database               = $row.Database
                        DatabaseMaxDop         = $row.DatabaseMaxDop
                        CurrentInstanceMaxDop  = $row.CurrentInstanceMaxDop
                        RecommendedMaxDop      = $row.RecommendedMaxDop
                        OldDatabaseMaxDopValue = $row.OldDatabaseMaxDopValue
                        OldInstanceMaxDopValue = $row.OldInstanceMaxDopValue
                    }
                }
                catch {
                    Stop-Function -Message "Could not modify Max Degree of Parallelism for $server."  -ErrorRecord $_ -Target $server -Continue
                }
            }

            if ($dbscopedconfiguration) {
                Select-DefaultView -InputObject $results -Property InstanceName, Database, OldDatabaseMaxDopValue, @{ name = "CurrentDatabaseMaxDopValue"; expression = { $_.DatabaseMaxDop } }
            }
            else {
                Select-DefaultView -InputObject $results -Property InstanceName, OldInstanceMaxDopValue, CurrentInstanceMaxDop
            }
        }
    }
}