internal/configurations/configuration.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
<#
 
#-------------------------#
# Warning Warning Warning #
#-------------------------#
 
This is the global configuration management file.
 
DO NOT EDIT THIS FILE!!!!!
Disobedience shall be answered by the wrath of Fred.
You've been warned.
;)
 
The purpose of this file is to manage the configuration system.
That means, messing with this may mess with every function using this infrastructure.
Don't, unless you know what you do.
 
#---------------------------------------#
# Implementing the configuration system #
#---------------------------------------#
 
The configuration system is designed, to keep as much hard coded configuration out of the functions.
Instead we keep it in a central location: The Configuration store (= this folder).
 
In Order to put something here, either find a configuration file whose topic suits you and add configuration there,
or create your own file. The configuration system is loaded last during module import process, so you have access to all
that dbatools has to offer (Keep module load times in mind though).
 
Examples are better than a thousand words:
 
a) Setting the configuration value
# Put this in a configuration file in this folder
Set-DbaConfig -Name 'Path.DbatoolsLog' -Value "$($env:AppData)\PowerShell\dbatools" -Default
 
b) Retrieving the configuration value in your function
# Put this in the function that uses this setting
$path = Get-DbaConfigValue -Name 'Path.DbatoolsLog' -FallBack $env:temp
 
# Explanation #
#-------------#
 
In step a), which is run during module import, we assign the configuration of the name 'Path.DbatoolsLog' the value "$($env:AppData)\PowerShell\dbatools"
Unless there already IS a value set to this name (that's what the '-Default' switch is doing).
That means, that if a user had a different configuration value in his profile, that value will win. Userchoice over preset.
ALL configurations defined by the module should be 'default' values.
 
In step b), which will be run whenever the function is called within which it is written, we retrieve the value stored behind the name 'Path.DbatoolsLog'.
If there is nothing there (for example, if the user accidentally removed or nulled the configuration), then it will fall back to using "$($env:temp)\dbatools.log"
 
#--------------------#
# Architecture Notes #
#--------------------#
 
In order to reduce import times, this is executed in a separate runspace.
 
#>


$scriptBlock = {
    Param (
        $DbatoolsConfig
    )
    $ModuleRoot = [Sqlcollaborative.Dbatools.dbaSystem.SystemHost]::ModuleBase

    #region Helper functions
    # Empty dummy, should not have a cmdletbinding in order to avoid errors.
    function Stop-Function { }

    $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText("$ModuleRoot\internal\Test-Bound.ps1"))), $null, $null)
    $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText("$ModuleRoot\internal\Register-DbaConfigValidation.ps1"))), $null, $null)
    $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText("$ModuleRoot\functions\Register-DbaConfig.ps1"))), $null, $null)
    $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText("$ModuleRoot\functions\Set-DbaConfig.ps1"))), $null, $null)
    #endregion Helper functions



    $configpath = "$ModuleRoot\internal\configurations"

    # Import configuration validation
    foreach ($file in (Get-ChildItem -Path "$configpath\validation")) {
        if ($script:doDotSource) { . $file.FullName }
        else { . ([scriptblock]::Create([io.file]::ReadAllText($file.FullName))) }
    }

    # Import other configuration files
    foreach ($file in (Get-ChildItem -Path "$configpath\settings")) {
        if ($script:doDotSource) { . $file.FullName }
        else { . ([scriptblock]::Create([io.file]::ReadAllText($file.FullName))) }
    }

    #region Import settings from registry
    if (-not [Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::ImportFromRegistryDone) {
        $common = 'PSPath', 'PSParentPath', 'PSChildName', 'PSDrive', 'PSProvider'

        function Convert-RegType {
            [CmdletBinding()]
            Param (
                [string]
                $Value
            )

            $index = $Value.IndexOf(":")
            if ($index -lt 1) { throw "No type identifier found!" }
            $type = $Value.Substring(0, $index).ToLower()
            $content = $Value.Substring($index + 1)

            switch ($type) {
                "bool" {
                    if ($content -eq "true") { return $true }
                    if ($content -eq "1") { return $true }
                    if ($content -eq "false") { return $false }
                    if ($content -eq "0") { return $false }
                    throw "Failed to interpret as bool: $content"
                }
                "int" { return ([int]$content) }
                "double" { return [double]$content }
                "long" { return [long]$content }
                "string" { return $content }
                "timespan" { return (New-Object System.TimeSpan($content)) }
                "datetime" { return (New-Object System.DateTime($content)) }
                "consolecolor" { return ([System.ConsoleColor]$content) }

                default { throw "Unknown type identifier" }
            }
        }

        #region Import from registry
        $config_hash = @{ }
        foreach ($item in ((Get-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\WindowsPowerShell\dbatools\Config\Default" -ErrorAction Ignore).PSObject.Properties | Where-Object Name -NotIn $common)) {
            try {
                $config_hash[$item.Name.ToLower()] = New-Object PSObject -Property @{
                    Name     = $item.Name
                    Enforced = $false
                    Value    = Convert-RegType -Value $item.Value
                }
            }
            catch {
                Write-Message -Level Warning -Message "Failed to interpret configuration entry from registry: $($item.Name)" -ErrorRecord $_
            }
        }
        foreach ($item in ((Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\WindowsPowerShell\dbatools\Config\Default" -ErrorAction Ignore).PSObject.Properties | Where-Object Name -NotIn $common)) {
            try {
                $config_hash[$item.Name.ToLower()] = New-Object PSObject -Property @{
                    Name     = $item.Name
                    Enforced = $false
                    Value    = Convert-RegType -Value $item.Value
                }
            }
            catch {
                Write-Message -Level Warning -Message "Failed to interpret configuration entry from registry: $($item.Name)" -ErrorRecord $_
            }
        }
        foreach ($item in ((Get-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\WindowsPowerShell\dbatools\Config\Enforced" -ErrorAction Ignore).PSObject.Properties | Where-Object Name -NotIn $common)) {
            try {
                $config_hash[$item.Name.ToLower()] = New-Object PSObject -Property @{
                    Name     = $item.Name
                    Enforced = $true
                    Value    = Convert-RegType -Value $item.Value
                }
            }
            catch {
                Write-Message -Level Warning -Message "Failed to interpret configuration entry from registry: $($item.Name)" -ErrorRecord $_
            }
        }
        foreach ($item in ((Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\WindowsPowerShell\dbatools\Config\Enforced" -ErrorAction Ignore).PSObject.Properties | Where-Object Name -NotIn $common)) {
            try {
                $config_hash[$item.Name.ToLower()] = New-Object PSObject -Property @{
                    Name     = $item.Name
                    Enforced = $true
                    Value    = Convert-RegType -Value $item.Value
                }
            }
            catch {
                Write-Message -Level Warning -Message "Failed to interpret configuration entry from registry: $($item.Name)" -ErrorRecord $_
            }
        }
        #endregion Import from registry

        foreach ($value in $config_hash.Values) {
            try {
                Set-DbaConfig -Name $value.Name -Value $value.Value -EnableException
                [Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::Configurations[$value.Name.ToLower()].PolicySet = $true
                [Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::Configurations[$value.Name.ToLower()].PolicyEnforced = $value.Enforced
            }
            catch { }
        }

        [Sqlcollaborative.Dbatools.Configuration.ConfigurationHost]::ImportFromRegistryDone = $true
    }
    #endregion Import settings from registry

    #region Implement user profile
    if ($DbatoolsConfig -ne $null) {
        if ($DbatoolsConfig.GetType().FullName -eq "System.Management.Automation.ScriptBlock") {
            [System.Management.Automation.ScriptBlock]::Create($DbatoolsConfig.ToString()).Invoke()
        }
    }
    #endregion Implement user profile
}
if ($script:serialImport) {
    $scriptBlock.Invoke($global:dbatools_config)
}
else {
    $script:dbatoolsConfigRunspace = [System.Management.Automation.PowerShell]::Create()
    try { $script:dbatoolsConfigRunspace.Runspace.Name = "dbatools-import-config" }
    catch { }
    $script:dbatoolsConfigRunspace.AddScript($scriptBlock).AddArgument($global:dbatools_config)
    $script:dbatoolsConfigRunspace.BeginInvoke()
}