internal/configurations/configuration.ps1

<#
 
#-------------------------#
# 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\functions\Test-Bound.ps1"))), $null, $null)
    $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText("$ModuleRoot\internal\functions\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()
}