functions/configuration/Register-DbatoolsConfig.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
function Register-DbatoolsConfig
{
<#
    .SYNOPSIS
        Registers an existing configuration object in registry.
     
    .DESCRIPTION
        Registers an existing configuration object in registry.
        This allows simple persisting of settings across powershell consoles.
        It also can be used to generate a registry template, which can then be used to create policies.
     
    .PARAMETER Config
        The configuration object to write to registry.
        Can be retrieved using Get-DbatoolsConfig.
     
    .PARAMETER FullName
        The full name of the setting to be written to registry.
     
    .PARAMETER Module
        The name of the module, whose settings should be written to registry.
     
    .PARAMETER Name
        Default: "*"
        Used in conjunction with the -Module parameter to restrict the number of configuration items written to registry.
     
    .PARAMETER Scope
        Default: UserDefault
        Who will be affected by this export how? Current user or all? Default setting or enforced?
        Legal values: UserDefault, UserMandatory, SystemDefault, SystemMandatory
     
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions.
        This is less user friendly, but allows catching exceptions in calling scripts.
     
    .EXAMPLE
        PS C:\> Get-DbatoolsConfig message.style.* | Register-DbatoolsConfig
     
        Retrieves all configuration items that that start with message.style. and registers them in registry for the current user.
     
    .EXAMPLE
        PS C:\> Register-DbatoolsConfig -FullName "message.consoleoutput.disable" -Scope SystemDefault
     
        Retrieves the configuration item "message.consoleoutput.disable" and registers it in registry as the default setting for all users on this machine.
     
    .EXAMPLE
        PS C:\> Register-DbatoolsConfig -Module Message -Scope SystemMandatory
     
        Retrieves all configuration items of the module Message, then registers them in registry to enforce them for all users on the current system.
#>

    [CmdletBinding(DefaultParameterSetName = "Default")]
    Param (
        [Parameter(ParameterSetName = "Default", Position = 0, ValueFromPipeline = $true)]
        [Sqlcollaborative.Dbatools.Configuration.Config[]]
        $Config,
        
        [Parameter(ParameterSetName = "Default", Position = 0, ValueFromPipeline = $true)]
        [string[]]
        $FullName,
        
        [Parameter(Mandatory = $true, ParameterSetName = "Name", Position = 0)]
        [string]
        $Module,
        
        [Parameter(ParameterSetName = "Name", Position = 1)]
        [string]
        $Name = "*",
        
        [Sqlcollaborative.Dbatools.Configuration.ConfigScope]
        $Scope = "UserDefault",
        
        [switch]
        $EnableException
    )
    
    begin
    {
        if ($script:NoRegistry -and ($Scope -band 14))
        {
            Stop-Function -Message "Cannot register configurations on non-windows machines to registry. Please specify a file-based scope" -Tag 'NotSupported' -Category NotImplemented
            return
        }
        
        # Linux and MAC default to local user store file
        if ($script:NoRegistry -and ($Scope -eq "UserDefault"))
        {
            $Scope = [Sqlcollaborative.Dbatools.Configuration.ConfigScope]::FileUserLocal
        }
        # Linux and MAC get redirection for SystemDefault to FileSystem
        if ($script:NoRegistry -and ($Scope -eq "SystemDefault"))
        {
            $Scope = [Sqlcollaborative.Dbatools.Configuration.ConfigScope]::FileSystem
        }
        
        $parSet = $PSCmdlet.ParameterSetName
        
        function Write-Config
        {
            [CmdletBinding()]
            Param (
                [Sqlcollaborative.Dbatools.Configuration.Config]
                $Config,
                
                [Sqlcollaborative.Dbatools.Configuration.ConfigScope]
                $Scope,
                
                [bool]
                $EnableException,
                
                [string]
                $FunctionName = (Get-PSCallStack)[0].Command
            )
            
            if (-not $Config -or ($Config.RegistryData -eq "<type not supported>"))
            {
                Stop-Function -Message "Invalid Input, cannot export $($Config.FullName), type not supported" -EnableException $EnableException -Category InvalidArgument -Tag "config", "fail" -Target $Config -FunctionName $FunctionName
                return
            }
            
            try
            {
                Write-Message -Level Verbose -Message "Registering $($Config.FullName) for $Scope" -Tag "Config" -Target $Config -FunctionName $FunctionName
                #region User Default
                if (1 -band $Scope)
                {
                    Ensure-RegistryPath -Path $script:path_RegistryUserDefault -ErrorAction Stop
                    Set-ItemProperty -Path $script:path_RegistryUserDefault -Name $Config.FullName -Value $Config.RegistryData -ErrorAction Stop
                }
                #endregion User Default
                
                #region User Mandatory
                if (2 -band $Scope)
                {
                    Ensure-RegistryPath -Path $script:path_RegistryUserEnforced -ErrorAction Stop
                    Set-ItemProperty -Path $script:path_RegistryUserEnforced -Name $Config.FullName -Value $Config.RegistryData -ErrorAction Stop
                }
                #endregion User Mandatory
                
                #region System Default
                if (4 -band $Scope)
                {
                    Ensure-RegistryPath -Path $script:path_RegistryMachineDefault -ErrorAction Stop
                    Set-ItemProperty -Path $script:path_RegistryMachineDefault -Name $Config.FullName -Value $Config.RegistryData -ErrorAction Stop
                }
                #endregion System Default
                
                #region System Mandatory
                if (8 -band $Scope)
                {
                    Ensure-RegistryPath -Path $script:path_RegistryMachineEnforced -ErrorAction Stop
                    Set-ItemProperty -Path $script:path_RegistryMachineEnforced -Name $Config.FullName -Value $Config.RegistryData -ErrorAction Stop
                }
                #endregion System Mandatory
            }
            catch
            {
                Stop-Function -Message "Failed to export $($Config.FullName), to scope $Scope" -EnableException $EnableException -Tag "config", "fail" -Target $Config -ErrorRecord $_ -FunctionName $FunctionName
                return
            }
        }
        
        function Ensure-RegistryPath
        {
            [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseApprovedVerbs", "")]
            [CmdletBinding()]
            Param (
                [string]
                $Path
            )
            
            if (-not (Test-Path $Path))
            {
                $null = New-Item $Path -Force
            }
        }
        
        # For file based persistence
        $configurationItems = @()
    }
    process
    {
        if (Test-FunctionInterrupt) { return }
        
        #region Registry Based
        if ($Scope -band 15)
        {
            switch ($parSet)
            {
                "Default"
                {
                    foreach ($item in $Config)
                    {
                        Write-Config -Config $item -Scope $Scope -EnableException $EnableException
                    }
                    
                    foreach ($item in $FullName)
                    {
                        if ([Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::Configurations.ContainsKey($item.ToLower()))
                        {
                            Write-Config -Config ([Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::Configurations[$item.ToLower()]) -Scope $Scope -EnableException $EnableException
                        }
                    }
                }
                "Name"
                {
                    foreach ($item in ([Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::Configurations.Values | Where-Object Module -EQ $Module | Where-Object Name -Like $Name))
                    {
                        Write-Config -Config $item -Scope $Scope -EnableException $EnableException
                    }
                }
            }
        }
        #endregion Registry Based
        
        #region File Based
        else
        {
            switch ($parSet)
            {
                "Default"
                {
                    foreach ($item in $Config)
                    {
                        if ($configurationItems.FullName -notcontains $item.FullName) { $configurationItems += $item }
                    }
                    
                    foreach ($item in $FullName)
                    {
                        if (($configurationItems.FullName -notcontains $item) -and ([Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::Configurations.ContainsKey($item.ToLower())))
                        {
                            $configurationItems += [Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::Configurations[$item.ToLower()]
                        }
                    }
                }
                "Name"
                {
                    foreach ($item in ([Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::Configurations.Values | Where-Object Module -EQ $Module | Where-Object Name -Like $Name))
                    {
                        if ($configurationItems.FullName -notcontains $item.FullName) { $configurationItems += $item }
                    }
                }
            }
        }
        #endregion File Based
    }
    end
    {
        if (Test-FunctionInterrupt) { return }
        
        #region Finish File Based Persistence
        if ($Scope -band 16)
        {
            Write-DbatoolsConfigFile -Config $configurationItems -Path (Join-Path $script:path_FileUserLocal "psf_config.json")
        }
        if ($Scope -band 32)
        {
            Write-DbatoolsConfigFile -Config $configurationItems -Path (Join-Path $script:path_FileUserShared "psf_config.json")
        }
        if ($Scope -band 64)
        {
            Write-DbatoolsConfigFile -Config $configurationItems -Path (Join-Path $script:path_FileSystem "psf_config.json")
        }
        #endregion Finish File Based Persistence
    }
}