functions/Get-DbaSpConfigure.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
function Get-DbaSpConfigure {
    <#
    .SYNOPSIS
        Returns all server level system configuration (sys.configuration/sp_configure) information
 
    .DESCRIPTION
        This function returns server level system configuration (sys.configuration/sp_configure) information. The information is gathered through SMO Configuration.Properties.
        The data includes the default value for each configuration, for quick identification of values that may have been changed.
 
    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input
 
    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).
 
        Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.
 
        For MFA support, please use Connect-DbaInstance.
 
    .PARAMETER Name
        Return only specific configurations. Name can be either values from (sys.configuration/sp_configure) or from SMO object
 
    .PARAMETER ExcludeName
        Exclude specific configurations. Name can be either values from (sys.configuration/sp_configure) or from SMO object
 
    .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: SpConfig, Configure, Configuration
        Author: Nic Cain, https://sirsql.net/
 
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT
 
    .LINK
        https://dbatools.io/Get-DbaSpConfigure
 
    .INPUTS
        A DbaInstanceParameter representing an array of SQL Server instances.
 
    .OUTPUTS
        Returns PSCustomObject with properties ServerName, ComputerName, InstanceName, SqlInstance, Name, DisplayName, Description, IsAdvanced, IsDynamic, MinValue, MaxValue, ConfiguredValue, RunningValue, DefaultValue, IsRunningDefaultValue
 
    .EXAMPLE
        PS C:\> Get-DbaSpConfigure -SqlInstance localhost
 
        Returns all system configuration information on the localhost.
 
    .EXAMPLE
        PS C:\> 'localhost','localhost\namedinstance' | Get-DbaSpConfigure
 
        Returns system configuration information on multiple instances piped into the function
 
    .EXAMPLE
        PS C:\> Get-DbaSpConfigure -SqlInstance sql2012 -Name 'max server memory (MB)'
 
        Returns only the system configuration for MaxServerMemory on sql2012.
 
    .EXAMPLE
        PS C:\> Get-DbaSpConfigure -SqlInstance sql2012 -ExcludeName 'max server memory (MB)', RemoteAccess | Out-GridView
 
        Returns system configuration information on sql2012 but excludes for max server memory (MB) and remote access. Values returned in grid view
 
    .EXAMPLE
        PS C:\> $cred = Get-Credential SqlCredential
        PS C:\> 'sql2012' | Get-DbaSpConfigure -SqlCredential $cred -Name RemoteAccess, 'max server memory (MB)' -ExcludeName 'remote access' | Out-GridView
 
        Returns system configuration information on sql2012 using SQL Server Authentication. Only MaxServerMemory is returned as RemoteAccess was also excluded.
 
    #>

    [CmdletBinding()]
    param (
        [parameter(Mandatory, ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [Alias("Config", "ConfigName")]
        [string[]]$Name,
        [string[]]$ExcludeName,
        [switch]$EnableException
    )
    begin {
        $smoName = [pscustomobject]@{
            "Ad Hoc Distributed Queries"         = "AdHocDistributedQueriesEnabled"
            "affinity I/O mask"                  = "AffinityIOMask"
            "affinity mask"                      = "AffinityMask"
            "affinity64 I/O mask"                = "Affinity64IOMask"
            "affinity64 mask"                    = "Affinity64Mask"
            "Agent XPs"                          = "AgentXPsEnabled"
            "allow updates"                      = "AllowUpdates"
            "awe enabled"                        = "AweEnabled"
            "backup compression default"         = "DefaultBackupCompression"
            "blocked process threshold"          = "BlockedProcessThreshold"
            "blocked process threshold (s)"      = "BlockedProcessThreshold"
            "c2 audit mode"                      = "C2AuditMode"
            "clr enabled"                        = "IsSqlClrEnabled"
            "common criteria compliance enabled" = "CommonCriteriaComplianceEnabled"
            "contained database authentication"  = "ContainmentEnabled"
            "cost threshold for parallelism"     = "CostThresholdForParallelism"
            "cross db ownership chaining"        = "CrossDBOwnershipChaining"
            "cursor threshold"                   = "CursorThreshold"
            "Database Mail XPs"                  = "DatabaseMailEnabled"
            "default full-text language"         = "DefaultFullTextLanguage"
            "default language"                   = "DefaultLanguage"
            "default trace enabled"              = "DefaultTraceEnabled"
            "disallow results from triggers"     = "DisallowResultsFromTriggers"
            "EKM provider enabled"               = "ExtensibleKeyManagementEnabled"
            "filestream access level"            = "FilestreamAccessLevel"
            "fill factor (%)"                    = "FillFactor"
            "ft crawl bandwidth (max)"           = "FullTextCrawlBandwidthMax"
            "ft crawl bandwidth (min)"           = "FullTextCrawlBandwidthMin"
            "ft notify bandwidth (max)"          = "FullTextNotifyBandwidthMax"
            "ft notify bandwidth (min)"          = "FullTextNotifyBandwidthMin"
            "index create memory (KB)"           = "IndexCreateMemory"
            "in-doubt xact resolution"           = "InDoubtTransactionResolution"
            "lightweight pooling"                = "LightweightPooling"
            "locks"                              = "Locks"
            "max degree of parallelism"          = "MaxDegreeOfParallelism"
            "max full-text crawl range"          = "FullTextCrawlRangeMax"
            "max server memory (MB)"             = "MaxServerMemory"
            "max text repl size (B)"             = "ReplicationMaxTextSize"
            "max worker threads"                 = "MaxWorkerThreads"
            "media retention"                    = "MediaRetention"
            "min memory per query (KB)"          = "MinMemoryPerQuery"
            "min server memory (MB)"             = "MinServerMemory"
            "nested triggers"                    = "NestedTriggers"
            "network packet size (B)"            = "NetworkPacketSize"
            "Ole Automation Procedures"          = "OleAutomationProceduresEnabled"
            "open objects"                       = "OpenObjects"
            "optimize for ad hoc workloads"      = "OptimizeAdhocWorkloads"
            "PH timeout (s)"                     = "ProtocolHandlerTimeout"
            "precompute rank"                    = "PrecomputeRank"
            "priority boost"                     = "PriorityBoost"
            "query governor cost limit"          = "QueryGovernorCostLimit"
            "query wait (s)"                     = "QueryWait"
            "recovery interval (min)"            = "RecoveryInterval"
            "remote access"                      = "RemoteAccess"
            "remote admin connections"           = "RemoteDacConnectionsEnabled"
            "remote data archive"                = "RemoteDataArchiveEnabled"
            "remote login timeout (s)"           = "RemoteLoginTimeout"
            "remote proc trans"                  = "RemoteProcTrans"
            "remote query timeout (s)"           = "RemoteQueryTimeout"
            "Replication XPs"                    = "ReplicationXPsEnabled"
            "scan for startup procs"             = "ScanForStartupProcedures"
            "server trigger recursion"           = "ServerTriggerRecursionEnabled"
            "set working set size"               = "SetWorkingSetSize"
            "show advanced options"              = "ShowAdvancedOptions"
            "SMO and DMO XPs"                    = "SmoAndDmoXPsEnabled"
            "SQL Mail XPs"                       = "SqlMailXPsEnabled"
            "transform noise words"              = "TransformNoiseWords"
            "two digit year cutoff"              = "TwoDigitYearCutoff"
            "user connections"                   = "UserConnections"
            "user options"                       = "UserOptions"
            "Web Assistant Procedures"           = "WebXPsEnabled"
            "xp_cmdshell"                        = "XPCmdShellEnabled"
            # Configurations without defined names - Created dummy entries
            "access check cache bucket count"    = "AccessCheckCacheBucketCount"
            "access check cache quota"           = "AccessCheckCacheQuota"
            "allow polybase export"              = "AllowPolybaseExport"
            "automatic soft-NUMA disabled"       = "AutomaticSoftnumaDisabled"
            "backup checksum default"            = "BackupChecksumDefault"
            "clr strict security"                = "ClrStrictSecurity"
            "external scripts enabled"           = "ExternalScriptsEnabled"
            "hadoop connectivity"                = "HadoopConnectivity"
            "polybase network encryption"        = "PolybaseNetworkEncryption"
            "User Instance Timeout"              = "UserInstanceTimeout"
            "user instances enabled"             = "UserInstancesEnabled"
        }
    }
    process {
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            } catch {
                Stop-Function -Message "Failed to process Instance $Instance" -ErrorRecord $_ -Target $instance -Continue
            }

            #Get a list of the configuration Properties. This collection matches entries in sys.configurations
            try {
                $proplist = $server.Configuration.Properties
            } catch {
                Stop-Function -Message "Unable to gather configuration properties $instance" -Target $instance -ErrorRecord $_ -Continue
            }

            if ($Name) {
                $proplist = $proplist | Where-Object { ($_.DisplayName -in $Name -or ($smoName).$($_.DisplayName) -in $Name) }
            }

            if (Test-Bound "ExcludeName") {
                $proplist = $proplist | Where-Object { ($_.DisplayName -NotIn $ExcludeName -and ($smoName).$($_.DisplayName) -NotIn $ExcludeName) }
            }

            #Grab the default sp_configure property values from the external function
            $defaultConfigs = (Get-SqlDefaultSpConfigure -SqlVersion $server.VersionMajor).psobject.properties;

            #Iterate through the properties to get the configuration settings
            foreach ($prop in $proplist) {
                $defaultConfig = $defaultConfigs | Where-Object { $_.Name -eq $prop.DisplayName };

                if ($defaultConfig.Value -eq $prop.RunValue) { $isDefault = $true }
                else { $isDefault = $false }

                #Ignores properties that are not valid on this version of SQL
                if (!([string]::IsNullOrEmpty($prop.RunValue))) {

                    $DisplayName = $prop.DisplayName
                    [pscustomobject]@{
                        ServerName            = $server.Name
                        ComputerName          = $server.ComputerName
                        InstanceName          = $server.ServiceName
                        SqlInstance           = $server.DomainInstanceName
                        Name                  = ($smoName).$DisplayName
                        DisplayName           = $DisplayName
                        Description           = $prop.Description
                        IsAdvanced            = $prop.IsAdvanced
                        IsDynamic             = $prop.IsDynamic
                        MinValue              = $prop.Minimum
                        MaxValue              = $prop.Maximum
                        ConfiguredValue       = $prop.ConfigValue
                        RunningValue          = $prop.RunValue
                        DefaultValue          = $defaultConfig.Value
                        IsRunningDefaultValue = $isDefault
                        Parent                = $server
                        ConfigName            = ($smoName).$DisplayName
                        Property              = $prop
                    } | Select-DefaultView -ExcludeProperty ServerName, Parent, ConfigName, Property
                }
            }
        }
    }
}