DCManagement.psm1

$script:ModuleRoot = $PSScriptRoot
$script:ModuleVersion = (Import-PowerShellDataFile -Path "$($script:ModuleRoot)\DCManagement.psd1").ModuleVersion

# Detect whether at some level dotsourcing was enforced
$script:doDotSource = Get-PSFConfigValue -FullName DCManagement.Import.DoDotSource -Fallback $false
if ($DCManagement_dotsourcemodule) { $script:doDotSource = $true }

<#
Note on Resolve-Path:
All paths are sent through Resolve-Path/Resolve-PSFPath in order to convert them to the correct path separator.
This allows ignoring path separators throughout the import sequence, which could otherwise cause trouble depending on OS.
Resolve-Path can only be used for paths that already exist, Resolve-PSFPath can accept that the last leaf my not exist.
This is important when testing for paths.
#>


# Detect whether at some level loading individual module files, rather than the compiled module was enforced
$importIndividualFiles = Get-PSFConfigValue -FullName DCManagement.Import.IndividualFiles -Fallback $false
if ($DCManagement_importIndividualFiles) { $importIndividualFiles = $true }
if (Test-Path (Resolve-PSFPath -Path "$($script:ModuleRoot)\..\.git" -SingleItem -NewChild)) { $importIndividualFiles = $true }
if ("<was compiled>" -eq '<was not compiled>') { $importIndividualFiles = $true }
    
function Import-ModuleFile
{
    <#
        .SYNOPSIS
            Loads files into the module on module import.
         
        .DESCRIPTION
            This helper function is used during module initialization.
            It should always be dotsourced itself, in order to proper function.
             
            This provides a central location to react to files being imported, if later desired
         
        .PARAMETER Path
            The path to the file to load
         
        .EXAMPLE
            PS C:\> . Import-ModuleFile -File $function.FullName
     
            Imports the file stored in $function according to import policy
    #>

    [CmdletBinding()]
    Param (
        [string]
        $Path
    )
    
    $resolvedPath = $ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($Path).ProviderPath
    if ($doDotSource) { . $resolvedPath }
    else { $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText($resolvedPath))), $null, $null) }
}

#region Load individual files
if ($importIndividualFiles)
{
    # Execute Preimport actions
    . Import-ModuleFile -Path "$ModuleRoot\internal\scripts\preimport.ps1"
    
    # Import all internal functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\internal\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Import all public functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Execute Postimport actions
    . Import-ModuleFile -Path "$ModuleRoot\internal\scripts\postimport.ps1"
    
    # End it here, do not load compiled code below
    return
}
#endregion Load individual files

#region Load compiled code
<#
This file loads the strings documents from the respective language folders.
This allows localizing messages and errors.
Load psd1 language files for each language you wish to support.
Partial translations are acceptable - when missing a current language message,
it will fallback to English or another available language.
#>

Import-PSFLocalizedString -Path "$($script:ModuleRoot)\en-us\*.psd1" -Module 'DCManagement' -Language 'en-US'

function New-Password
{
    <#
        .SYNOPSIS
            Generate a new, complex password.
         
        .DESCRIPTION
            Generate a new, complex password.
         
        .PARAMETER Length
            The length of the password calculated.
            Defaults to 32
 
        .PARAMETER AsSecureString
            Returns the password as secure string.
         
        .EXAMPLE
            PS C:\> New-Password
 
            Generates a new 32v character password.
    #>

    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")]
    [CmdletBinding()]
    Param (
        [int]
        $Length = 32,

        [switch]
        $AsSecureString
    )
    
    begin
    {
        $characters = @{
            0 = @('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z')
            1 = @('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z')
            2 = @(0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9)
            3 = @('#','$','%','&',"'",'(',')','*','+',',','-','.','/',':',';','<','=','>','?','@')
            4 = @('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z')
            5 = @('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z')
            6 = @(0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9)
            7 = @('#','$','%','&',"'",'(',')','*','+',',','-','.','/',':',';','<','=','>','?','@')
        }
    }
    process
    {
        $letters = foreach ($number in (1..$Length)) {
            $characters[(($number % 4) + (1..4 | Get-Random))] | Get-Random
        }
        if ($AsSecureString) { $letters -join "" | ConvertTo-SecureString -AsPlainText -Force }
        else { $letters -join "" }
    }
}

function Install-DCChildDomain
{
    <#
    .SYNOPSIS
        Installs a child domain.
     
    .DESCRIPTION
        Installs a child domain.
     
    .PARAMETER ComputerName
        The server to promote to a DC hosting a new subdomain.
     
    .PARAMETER Credential
        The credentials to use for connecting to the DC-to-be.
     
    .PARAMETER DomainName
        The name of the domain to install.
        Note: Only specify the first DNS element, not the full fqdn of the domain.
        (The component usually representing the Netbios Name)
     
    .PARAMETER ParentDomainName
        The FQDN of the parent domain.
     
    .PARAMETER NetBiosName
        The NetBios name of the domain.
        Will use the DomainName if not specified.
     
    .PARAMETER SafeModeAdministratorPassword
        The SafeModeAdministratorPassword specified during domain creation.
        If not specified, a random password will be chosen.
        The password is part of the return values.
     
    .PARAMETER EnterpriseAdminCredential
        The Credentials of an Enterprise administrator.
        Will prompt for credentials if not specified.
     
    .PARAMETER NoDNS
        Disables installation and configuration of the DNS role as part of the installation.
     
    .PARAMETER NoReboot
        Prevents reboot of the server after installation.
        Note: Generally a reboot is required before proceeding, disabling this will lead to having to manually reboot the computer.
     
    .PARAMETER LogPath
        The path where the NTDS logs should be stored.
     
    .PARAMETER Sysvolpath
        The path where SYSVOL should be stored.
     
    .PARAMETER DatabasePath
        The path where the NTDS database is being stored.
     
    .PARAMETER NoResultCache
        Disables caching of the command's return object.
        By default, this command will cache the return object as a global variable.
     
    .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.
     
    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
     
    .PARAMETER WhatIf
        If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
     
    .EXAMPLE
        PS C:\> Install-DCChildDomain -ComputerName 10.1.2.3 -Credential $cred -DomainName corp -ParentDomainName contoso.com
 
        Will install the childdomain corp.contoso.com under the domain contoso.com on the server 10.1.2.3.
    #>

    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidGlobalVars", "")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseDeclaredVarsMoreThanAssignments", "")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
    [CmdletBinding(SupportsShouldProcess = $true)]
    Param (
        [PSFComputer]
        $ComputerName = 'localhost',

        [PSCredential]
        $Credential,

        [Parameter(Mandatory = $true)]
        [PsfValidatePattern('^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-_]{0,61}[a-zA-Z0-9])$', ErrorString = 'DCManagement.Validate.Child.DomainName')]
        [string]
        $DomainName,

        [Parameter(Mandatory = $true)]
        [PsfValidatePattern('^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-_]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-_]{0,61}[a-zA-Z0-9])){1,}$', ErrorString = 'DCManagement.Validate.Parent.DnsDomainName')]
        [string]
        $ParentDomainName,

        [string]
        $NetBiosName,

        [securestring]
        $SafeModeAdministratorPassword = (New-Password -Length 32 -AsSecureString),

        [PSCredential]
        $EnterpriseAdminCredential = (Get-Credential -Message "Enter credentials for Enterprise Administrator to create child domain"),

        [switch]
        $NoDNS = (Get-PSFConfigValue -FullName 'DCManagement.Defaults.NoDNS'),

        [switch]
        $NoReboot = (Get-PSFConfigValue -FullName 'DCManagement.Defaults.NoReboot'),

        [string]
        $LogPath = (Get-PSFConfigValue -FullName 'DCManagement.Defaults.LogPath'),

        [string]
        $Sysvolpath = (Get-PSFConfigValue -FullName 'DCManagement.Defaults.SysvolPath'),

        [string]
        $DatabasePath = (Get-PSFConfigValue -FullName 'DCManagement.Defaults.DatabasePath'),

        [switch]
        $NoResultCache,

        [switch]
        $EnableException
    )
    
    begin
    {
        #region Scriptblock
        $scriptBlock = {
            param ($Configuration)

            function New-Result {
                [CmdletBinding()]
                param (
                    [ValidateSet('Success', 'Error')]
                    [string]
                    $Status = 'Success',

                    [string]
                    $Message,

                    $ErrorRecord,

                    $Data
                )

                [PSCustomObject]@{
                    Status = $Status
                    Success = $Status -eq 'Success'
                    Message = $Message
                    Error = $ErrorRecord
                    Data = $Data
                    SafeModeAdminPassword = $null
                }
            }
            
            # Check whether domain member
            $computerSystem = Get-CimInstance win32_ComputerSystem
            if ($computerSystem.PartOfDomain) {
                New-Result -Status Error -Message "Computer $env:COMPUTERNAME is part of AD domain: $($computerSystem.Domain)"
                return
            }

            $parameters = @{
                NewDomainName = $Configuration.NewDomainName
                NewDomainNetBiosName = $Configuration.NewDomainNetBiosName
                ParentDomainName = $Configuration.ParentDomainName
                Credential = $Configuration.EnterpriseAdminCredential
                DomainMode = 'Win2012R2'
                DatabasePath = $Configuration.DatabasePath
                LogPath = $Configuration.LogPath
                SysvolPath = $Configuration.Sysvol
                InstallDNS = $Configuration.InstallDNS
                SafeModeAdministratorPassword = $Configuration.SafeModeAdministratorPassword
                NoRebootOnCompletion = $Configuration.NoRebootOnCompletion
            }

            # Test Installation
            $testResult = Test-ADDSDomainInstallation @parameters -WarningAction SilentlyContinue
            if ($testResult.Status -eq "Error") {
                New-Result -Status Error -Message "Failed validating Domain Installation: $($testResult.Message)" -Data $testResult
                return
            }

            # Execute Installation
            try {
                $resultData = Install-ADDSDomain @parameters -ErrorAction Stop -Confirm:$false -WarningAction SilentlyContinue
                if ($resultData.Status -eq "Error") {
                    New-Result -Status Error -Message "Failed installing domain: $($resultData.Message)" -Data $resultData
                    return
                }
                New-Result -Status 'Success' -Message "Domain $($Configuration.NewDomainName) successfully installed" -Data $resultData
                return
            }
            catch {
                New-Result -Status Error -Message "Error executing domain deployment: $_" -ErrorRecord $_
                return
            }
        }
        #endregion Scriptblock
    }
    process
    {
        if (-not $NetBiosName) { $NetBiosName = $DomainName }
        $configuration = [PSCustomObject]@{
            NewDomainName = $DomainName
            NewDomainNetBiosName = $NetBiosName
            ParentDomainName = $ParentDomainName
            EnterpriseAdminCredential = $EnterpriseAdminCredential
            InstallDNS = (-not $NoDNS)
            LogPath = $LogPath
            SysvolPath = $SysvolPath
            DatabasePath = $DatabasePath
            NoRebootOnCompletion = $NoReboot
            SafeModeAdministratorPassword = $SafeModeAdministratorPassword
        }

        Invoke-PSFProtectedCommand -ActionString 'Install-DCChildDomain.Installing' -Target $DomainName -ScriptBlock {
            $result = Invoke-PSFCommand -ComputerName $ComputerName -Credential $Credential -ScriptBlock $scriptBlock -ErrorAction Stop -ArgumentList $configuration
            $result.SafeModeAdminPassword = $SafeModeAdministratorPassword
            $result = $result | Select-PSFObject -KeepInputObject -ScriptProperty @{
                Password = {
                    [PSCredential]::new("Foo", $this.SafeModeAdminPassword).GetNetworkCredential().Password
                }
            } -ShowProperty Success, Message
            if (-not $NoResultCache) {
                $global:DomainCreationResult = $result
            }
            $result
        } -EnableException $EnableException -PSCmdlet $PSCmdlet
        if (Test-PSFFunctionInterrupt) { return }
        
        if (-not $NoResultCache) {
            Write-PSFMessage -Level Host -String 'Install-DCChildDomain.Results' -StringValues $DomainName
        }
    }
}


function Install-DCDomainController
{
    <#
    .SYNOPSIS
        Adds a new domain controller to an existing domain.
     
    .DESCRIPTION
        Adds a new domain controller to an existing domain.
        The target computer cannot already be part of the domain.
     
    .PARAMETER ComputerName
        The target to promote to domain controller.
        Accepts and reuses an already established PowerShell Remoting Session.
     
    .PARAMETER Credential
        Credentials to use for authenticating to the computer account being promoted.
     
    .PARAMETER DomainName
        The fully qualified dns name of the domain to join the DC to.
     
    .PARAMETER DomainCredential
        Credentials to use when authenticating to the domain.
     
    .PARAMETER SafeModeAdministratorPassword
        The password to use as SafeModeAdministratorPassword.
        Autogenerates and reports a new password if not specified.
     
    .PARAMETER NoDNS
        Disable deploying a DNS service with the new domain controller.
     
    .PARAMETER NoReboot
        Prevent reboot after finishing deployment
     
    .PARAMETER LogPath
        The path where the DC will store the logs.
     
    .PARAMETER Sysvolpath
        The path where the DC will store sysvol.
     
    .PARAMETER DatabasePath
        The path where the DC will store NTDS Database.
 
    .PARAMETER NoResultCache
        Disables caching the result object of the operation.
        By default, this command will cache the result of the installation (including the SafeModeAdministratorPassword), to reduce the risk of user error.
     
    .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.
     
    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
     
    .PARAMETER WhatIf
        If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
     
    .EXAMPLE
        PS C:\> Install-DCDomainController -Computer dc2.contoso.com -Credential $localCred -DomainName 'contoso.com' -DomainCredential $domCred
 
        Joins the server dc2.contoso.com into the contoso.com domain, as a promoted domain controller using the specified credentials.
    #>

    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidGlobalVars", "")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseDeclaredVarsMoreThanAssignments", "")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
    [CmdletBinding(SupportsShouldProcess = $true)]
    Param (
        [PSFComputer]
        $ComputerName = 'localhost',

        [PSCredential]
        $Credential,

        [Parameter(Mandatory = $true)]
        [PsfValidatePattern('^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-_]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-_]{0,61}[a-zA-Z0-9])){1,}$', ErrorString = 'DCManagement.Validate.ForestRoot.DnsDomainName')]
        [string]
        $DomainName,

        [PSCredential]
        $DomainCredential = (Get-Credential -Message 'Specify domain admin credentials needed to authorize the promotion to domain controller'),

        [securestring]
        $SafeModeAdministratorPassword = (New-Password -Length 32 -AsSecureString),

        [switch]
        $NoDNS = (Get-PSFConfigValue -FullName 'DCManagement.Defaults.NoDNS'),

        [switch]
        $NoReboot = (Get-PSFConfigValue -FullName 'DCManagement.Defaults.NoReboot'),

        [string]
        $LogPath = (Get-PSFConfigValue -FullName 'DCManagement.Defaults.LogPath'),

        [string]
        $Sysvolpath = (Get-PSFConfigValue -FullName 'DCManagement.Defaults.SysvolPath'),

        [string]
        $DatabasePath = (Get-PSFConfigValue -FullName 'DCManagement.Defaults.DatabasePath'),

        [switch]
        $NoResultCache,

        [switch]
        $EnableException
    )
    
    begin
    {
        #region Main Scriptblock
        $scriptBlock = {
            param (
                $Configuration
            )
            function New-Result {
                [CmdletBinding()]
                param (
                    [ValidateSet('Success', 'Error')]
                    [string]
                    $Status = 'Success',

                    [string]
                    $Message,

                    $ErrorRecord,

                    $Data
                )

                [PSCustomObject]@{
                    Status = $Status
                    Success = $Status -eq 'Success'
                    Message = $Message
                    Error = $ErrorRecord
                    Data = $Data
                    SafeModeAdminPassword = $null
                }
            }
            
            # Check whether domain member
            $computerSystem = Get-CimInstance win32_ComputerSystem
            if ($computerSystem.PartOfDomain) {
                New-Result -Status Error -Message "Computer $env:COMPUTERNAME is part of AD domain: $($computerSystem.Domain)"
                return
            }

            $parameters = @{
                DomainName = $Configuration.DomainName
                Credential = $Configuration.DomainCredential
                DatabasePath = $Configuration.DatabasePath
                LogPath = $Configuration.LogPath
                SysvolPath = $Configuration.Sysvol
                InstallDNS = $Configuration.InstallDNS
                SafeModeAdministratorPassword = $Configuration.SafeModeAdministratorPassword
                NoRebootOnCompletion = $Configuration.NoRebootOnCompletion
            }
            
            # Test Installation
            $testResult = Test-ADDSDomainController @parameters -WarningAction SilentlyContinue
            if ($testResult.Status -eq "Error") {
                New-Result -Status Error -Message "Failed validating Domain Controller Installation: $($testResult.Message)" -Data $testResult
                return
            }

            # Execute Installation
            try {
                $resultData = Install-ADDSDomainController @parameters -ErrorAction Stop -Confirm:$false -WarningAction SilentlyContinue
                if ($resultData.Status -eq "Error") {
                    New-Result -Status Error -Message "Failed installing Domain Controller: $($resultData.Message)" -Data $resultData
                    return
                }
                New-Result -Status 'Success' -Message "Domain $($Configuration.DomainName) successfully installed" -Data $resultData
                return
            }
            catch {
                New-Result -Status Error -Message "Error executing Domain Controller deployment: $_" -ErrorRecord $_
                return
            }
        }
        #endregion Main Scriptblock
    }
    process
    {
        if (-not $NetBiosName) { $NetBiosName = $DnsName -split "\." | Select-Object -First 1 }
        $configuration = [PSCustomObject]@{
            DomainName = $DomainName
            DomainCredential = $DomainCredential
            SafeModeAdministratorPassword = $SafeModeAdministratorPassword
            InstallDNS = (-not $NoDNS)
            LogPath = $LogPath
            SysvolPath = $SysvolPath
            DatabasePath = $DatabasePath
            NoRebootOnCompletion = $NoReboot
        }
        
        Invoke-PSFProtectedCommand -ActionString 'Install-DCDomainController.Installing' -ActionStringValues $DomainName -Target $DnsName -ScriptBlock {
            $result = Invoke-PSFCommand -ComputerName $ComputerName -Credential $Credential -ScriptBlock $scriptBlock -ErrorAction Stop -ArgumentList $configuration
            $result.SafeModeAdminPassword = $SafeModeAdministratorPassword
            $result = $result | Select-PSFObject -KeepInputObject -ScriptProperty @{
                Password = {
                    [PSCredential]::new("Foo", $this.SafeModeAdminPassword).GetNetworkCredential().Password
                }
            } -ShowProperty Success, Message
            if (-not $NoResultCache) {
                $global:DCCreationResult = $result
            }
            $result
        } -EnableException $EnableException -PSCmdlet $PSCmdlet
        if (Test-PSFFunctionInterrupt) { return }

        if (-not $NoResultCache) {
            Write-PSFMessage -Level Host -String 'Install-DCDomainController.Results' -StringValues $DnsName
        }
    }
}


function Install-DCRootDomain
{
    <#
    .SYNOPSIS
        Deploys a new forest / root domain.
     
    .DESCRIPTION
        Deploys a new forest / root domain.
     
    .PARAMETER ComputerName
        The computer on which to install it.
        Uses WinRM / PowerShell remoting if not local execution.
     
    .PARAMETER Credential
        The credentials to use for this operation.
     
    .PARAMETER DnsName
        The name of the new domain & forest.
     
    .PARAMETER NetBiosName
        The netbios name of the new domain.
        If not specified, it will automatically use the first element of the DNS name
     
    .PARAMETER SafeModeAdministratorPassword
        The password to use as SafeModeAdministratorPassword.
        Autogenerates and reports a new password if not specified.
     
    .PARAMETER NoDNS
        Disable deploying a DNS service with the new forest.
     
    .PARAMETER NoReboot
        Prevent reboot after finishing deployment
     
    .PARAMETER LogPath
        The path where the DC will store the logs.
     
    .PARAMETER Sysvolpath
        The path where the DC will store sysvol.
     
    .PARAMETER DatabasePath
        The path where the DC will store NTDS Database.
 
    .PARAMETER NoResultCache
        Disables caching the result object of the operation.
        By default, this command will cache the result of the installation (including the SafeModeAdministratorPassword), to reduce the risk of user error.
     
    .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.
     
    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
     
    .PARAMETER WhatIf
        If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
     
    .EXAMPLE
        PS C:\> Install-DCRootDomain -DnsName 'contoso.com'
 
        Creates the forest "contoso.com" while promoting the computer as DC.
    #>

    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidGlobalVars", "")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseDeclaredVarsMoreThanAssignments", "")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
    [CmdletBinding(SupportsShouldProcess = $true)]
    Param (
        [PSFComputer]
        $ComputerName = 'localhost',

        [PSCredential]
        $Credential,

        [Parameter(Mandatory = $true)]
        [PsfValidatePattern('^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-_]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-_]{0,61}[a-zA-Z0-9])){1,}$', ErrorString = 'DCManagement.Validate.ForestRoot.DnsDomainName')]
        [string]
        $DnsName,

        [string]
        $NetBiosName,

        [securestring]
        $SafeModeAdministratorPassword = (New-Password -Length 32 -AsSecureString),

        [switch]
        $NoDNS = (Get-PSFConfigValue -FullName 'DCManagement.Defaults.NoDNS'),

        [switch]
        $NoReboot = (Get-PSFConfigValue -FullName 'DCManagement.Defaults.NoReboot'),

        [string]
        $LogPath = (Get-PSFConfigValue -FullName 'DCManagement.Defaults.LogPath'),

        [string]
        $Sysvolpath = (Get-PSFConfigValue -FullName 'DCManagement.Defaults.SysvolPath'),

        [string]
        $DatabasePath = (Get-PSFConfigValue -FullName 'DCManagement.Defaults.DatabasePath'),

        [switch]
        $NoResultCache,

        [switch]
        $EnableException
    )
    
    begin
    {
        #region Main Scriptblock
        $scriptBlock = {
            param (
                $Configuration
            )
            function New-Result {
                [CmdletBinding()]
                param (
                    [ValidateSet('Success', 'Error')]
                    [string]
                    $Status = 'Success',

                    [string]
                    $Message,

                    $ErrorRecord,

                    $Data
                )

                [PSCustomObject]@{
                    Status = $Status
                    Success = $Status -eq 'Success'
                    Message = $Message
                    Error = $ErrorRecord
                    Data = $Data
                    SafeModeAdminPassword = $null
                }
            }
            
            # Check whether domain member
            $computerSystem = Get-CimInstance win32_ComputerSystem
            if ($computerSystem.PartOfDomain) {
                New-Result -Status Error -Message "Computer $env:COMPUTERNAME is part of AD domain: $($computerSystem.Domain)"
                return
            }

            $parameters = @{
                DomainName = $Configuration.DnsName
                DomainMode = 'Win2012R2'
                DomainNetbiosName = $Configuration.NetBiosName
                ForestMode = 'Win2012R2'
                DatabasePath = $Configuration.DatabasePath
                LogPath = $Configuration.LogPath
                SysvolPath = $Configuration.Sysvol
                InstallDNS = $Configuration.InstallDNS
                SafeModeAdministratorPassword = $Configuration.SafeModeAdministratorPassword
                NoRebootOnCompletion = $Configuration.NoRebootOnCompletion
            }
            
            # Test Installation
            $testResult = Test-ADDSForestInstallation @parameters -WarningAction SilentlyContinue
            if ($testResult.Status -eq "Error") {
                New-Result -Status Error -Message "Failed validating Forest Installation: $($testResult.Message)" -Data $testResult
                return
            }

            # Execute Installation
            try {
                $resultData = Install-ADDSForest @parameters -ErrorAction Stop -Confirm:$false -WarningAction SilentlyContinue
                if ($resultData.Status -eq "Error") {
                    New-Result -Status Error -Message "Failed installing Forest: $($resultData.Message)" -Data $resultData
                    return
                }
                New-Result -Status 'Success' -Message "Domain $($Configuration.DnsName) successfully installed" -Data $resultData
                return
            }
            catch {
                New-Result -Status Error -Message "Error executing forest deployment: $_" -ErrorRecord $_
                return
            }
        }
        #endregion Main Scriptblock
    }
    process
    {
        if (-not $NetBiosName) { $NetBiosName = $DnsName -split "\." | Select-Object -First 1 }
        $configuration = [PSCustomObject]@{
            DnsName = $DnsName
            NetBiosName = $NetBiosName
            SafeModeAdministratorPassword = $SafeModeAdministratorPassword
            InstallDNS = (-not $NoDNS)
            LogPath = $LogPath
            SysvolPath = $SysvolPath
            DatabasePath = $DatabasePath
            NoRebootOnCompletion = $NoReboot
        }

        Invoke-PSFProtectedCommand -ActionString 'Install-DCRootDomain.Installing' -Target $DnsName -ScriptBlock {
            $result = Invoke-PSFCommand -ComputerName $ComputerName -Credential $Credential -ScriptBlock $scriptBlock -ErrorAction Stop -ArgumentList $configuration
            $result.SafeModeAdminPassword = $SafeModeAdministratorPassword
            $result = $result | Select-PSFObject -KeepInputObject -ScriptProperty @{
                Password = {
                    [PSCredential]::new("Foo", $this.SafeModeAdminPassword).GetNetworkCredential().Password
                }
            } -ShowProperty Success, Message
            if (-not $NoResultCache) {
                $global:ForestCreationResult = $result
            }
            $result
        } -EnableException $EnableException -PSCmdlet $PSCmdlet
        if (Test-PSFFunctionInterrupt) { return }
        
        if (-not $NoResultCache) {
            Write-PSFMessage -Level Host -String 'Install-DCRootDomain.Results' -StringValues $DnsName
        }
    }
}


<#
This is an example configuration file
 
By default, it is enough to have a single one of them,
however if you have enough configuration settings to justify having multiple copies of it,
feel totally free to split them into multiple files.
#>


<#
# Example Configuration
Set-PSFConfig -Module 'DCManagement' -Name 'Example.Setting' -Value 10 -Initialize -Validation 'integer' -Handler { } -Description "Example configuration setting. Your module can then use the setting using 'Get-PSFConfigValue'"
#>


Set-PSFConfig -Module 'DCManagement' -Name 'Import.DoDotSource' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be dotsourced on import. By default, the files of this module are read as string value and invoked, which is faster but worse on debugging."
Set-PSFConfig -Module 'DCManagement' -Name 'Import.IndividualFiles' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be imported individually. During the module build, all module code is compiled into few files, which are imported instead by default. Loading the compiled versions is faster, using the individual files is easier for debugging and testing out adjustments."

Set-PSFConfig -Module 'DCManagement' -Name 'Defaults.NoDNS' -Value $false -Validation bool -Initialize -Description 'Default value for "NoDNS" parameter when creating a new forest'
Set-PSFConfig -Module 'DCManagement' -Name 'Defaults.NoReboot' -Value $false -Validation bool -Initialize -Description 'Default value for "NoReboot" parameter when creating a new forest'
Set-PSFConfig -Module 'DCManagement' -Name 'Defaults.LogPath' -Value 'C:\Windows\NTDS' -Validation string -Initialize -Description 'Default value for "LogPath" parameter when creating a new forest'
Set-PSFConfig -Module 'DCManagement' -Name 'Defaults.SysvolPath' -Value 'C:\Windows\SYSVOL' -Validation string -Initialize -Description 'Default value for "SysvolPath" parameter when creating a new forest'
Set-PSFConfig -Module 'DCManagement' -Name 'Defaults.DatabasePath' -Value 'C:\Windows\NTDS' -Validation string -Initialize -Description 'Default value for "DatabasePath" parameter when creating a new forest'

<#
Stored scriptblocks are available in [PsfValidateScript()] attributes.
This makes it easier to centrally provide the same scriptblock multiple times,
without having to maintain it in separate locations.
 
It also prevents lengthy validation scriptblocks from making your parameter block
hard to read.
 
Set-PSFScriptblock -Name 'DCManagement.ScriptBlockName' -Scriptblock {
     
}
#>


<#
# Example:
Register-PSFTeppScriptblock -Name "DCManagement.alcohol" -ScriptBlock { 'Beer','Mead','Whiskey','Wine','Vodka','Rum (3y)', 'Rum (5y)', 'Rum (7y)' }
#>


<#
# Example:
Register-PSFTeppArgumentCompleter -Command Get-Alcohol -Parameter Type -Name DCManagement.alcohol
#>


New-PSFLicense -Product 'DCManagement' -Manufacturer 'Friedrich Weinmann' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2019-11-14") -Text @"
Copyright (c) 2019 Friedrich Weinmann
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"@

#endregion Load compiled code