Principal.psm1

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

# Detect whether at some level dotsourcing was enforced
$script:doDotSource = Get-PSFConfigValue -FullName Principal.Import.DoDotSource -Fallback $false
if ($Principal_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 Principal.Import.IndividualFiles -Fallback $false
if ($Principal_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
    foreach ($path in (& "$ModuleRoot\internal\scripts\preimport.ps1")) {
        . Import-ModuleFile -Path $path
    }
    
    # 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
    foreach ($path in (& "$ModuleRoot\internal\scripts\postimport.ps1")) {
        . Import-ModuleFile -Path $path
    }
    
    # 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 'Principal' -Language 'en-US'

function Clear-DomainCache
{
<#
    .SYNOPSIS
        Clears the domain data cache, resetting this module's domain memory.
     
    .DESCRIPTION
        Clears the domain data cache, resetting this module's domain memory.
     
    .EXAMPLE
        PS C:\> Clear-DomainCache
     
        Clears the domain data cache, resetting this module's domain memory.
#>

    [CmdletBinding()]
    param (
        
    )
    
    process
    {
        $script:domains = @{
            SID = @{ }
            Name = @{ }
            FQDN = @{ }
            NetBIOSName = @{ }
            UPN = @{ }
        }
        $script:domain_cache = @{
            
        }
    }
}


function Clear-PrincipalCache
{
<#
    .SYNOPSIS
        Clears the principal cache.
     
    .DESCRIPTION
        Clears the principal cache.
        This cache is used to optimize Resolve-Principal calls.
     
        Clearing it may become necessary when:
        - Encountering memory issues (when resolving tens of thousands of principals)
        - switching between multiple forests with the same domain names & Principal names (e.g.: from DEV to QA)
     
    .EXAMPLE
        PS C:\> Clear-PrincipalCache
     
        Clears the principal cache.
#>

    [CmdletBinding()]
    Param (
    
    )
    
    process
    {
        $script:principals = @{
            SID = @{ }
            UserPrincipalName = @{ }
        }
    }
}


function Get-Domain
{
    <#
    .SYNOPSIS
        Returns the direct domain object accessible via the server/credential parameter connection.
     
    .DESCRIPTION
        Returns the direct domain object accessible via the server/credential parameter connection.
        Caches data for subsequent calls.
     
    .PARAMETER Server
        The server / domain to work with.
     
    .PARAMETER Credential
        The credentials to use for this operation.
     
    .EXAMPLE
        PS C:\> Get-Domain @parameters
 
        Returns the domain associated with the specified connection information
    #>

    [CmdletBinding()]
    Param (
        [PSFComputer]
        $Server = '<Default>',
        
        [PSCredential]
        $Credential
    )
    
    process
    {
        if ($script:domain_cache["$Server"])
        {
            return $script:domain_cache["$Server"]
        }
        
        $parameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential
        try { $adObject = Get-ADDomain @parameters -ErrorAction Stop }
        catch { throw }
        $script:domain_cache["$Server"] = $adObject
        $adObject
    }
}

function Register-Domain
{
<#
    .SYNOPSIS
        Register an additional domain for principal resolution.
     
    .DESCRIPTION
        Register an additional domain for principal resolution.
        Domains are registered automatically as principal resolution occurs, but by pre-caching them, issues can be avoided.
     
        Specifically, resolving principals by UserPrincipalName can fail, if the UPN uses an additional UPN suffix, if the domains have not been pre-registered.
     
        Registering a domain will by default have all domains in that forest registered.
     
    .PARAMETER Server
        The server / domain to work with.
     
    .PARAMETER Credential
        The credentials to use for this operation.
     
    .PARAMETER NoRecurse
        Disables iterating over all domains in the forest when registering a domain.
     
    .EXAMPLE
        PS C:\> Register-Domain
     
        Registers (caches) the current domain - and all fellow domains in the current forest.
     
    .EXAMPLE
        PS C:\> Register-Domain -Server corp.contoso.com -Credential $cred -NoRecurse
     
        Registers (caches) the domain 'corp.contoso.com', using the specified credentials.
        Will not try to access the other domains in the forest.
#>

    [CmdletBinding()]
    param (
        [PSFComputer]
        $Server,
        
        [PSCredential]
        $Credential,
        
        [switch]
        $NoRecurse
    )
    
    begin
    {
        $parameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential
    }
    process
    {
        try { $adDomain = Get-ADDomain @parameters -ErrorAction Stop }
        catch { Stop-PSFFunction -String 'Register-Domain.ADAccess.Failed' -StringValues $Server -EnableException $true -ErrorRecord $_ -Cmdlet $PSCmdlet }
        
        $forest = Get-ADForest @parameters
        
        $data = [pscustomobject]@{
            DistinguishedName = $adDomain.DistinguishedName
            Name              = $adDomain.Name
            FQDN              = $adDomain.DNSRoot
            SID                  = $adDomain.DomainSID
            NetBIOSName          = $adDomain.NetBIOSName
            PDCEmulator          = $adDomain.PDCEmulator
            UPNs              = @($adDomain.DNSRoot) + @($forest.UPNSuffixes)
            Credential          = $Credential
            ADObject          = $adDomain
        }
        $script:domains.SID["$($data.SID)"] = $data
        $script:domains.Name[$data.Name] = $data
        $script:domains.FQDN[$data.FQDN] = $data
        $script:domains.NetBIOSName[$data.NetBIOSName] = $data
        foreach ($upn in $data.UPNs)
        {
            if (-not $script:domains.UPN[$upn]) { $script:domains.UPN[$upn] = @() }
            if ($script:domains.UPN[$upn].FQDN -contains $data.FQDN) { continue }
            $script:domains.UPN[$upn] += $data
        }
        
        if ($NoRecurse) { return }
        
        $cred = $PSBoundParameters | ConvertTo-PSFHashtable -Include Credential
        
        foreach ($domain in $forest.Domains)
        {
            if ($domain -eq $adDomain.DNSRoot) { continue }
            
            try { $domainObject = Get-ADDomain -Server $domain @cred -ErrorAction Stop }
            catch { continue }
            
            $data = [pscustomobject]@{
                DistinguishedName = $domainObject.DistinguishedName
                Name              = $domainObject.Name
                FQDN              = $domainObject.DNSRoot
                SID                  = $domainObject.DomainSID
                NetBIOSName          = $domainObject.NetBIOSName
                PDCEmulator          = $domainObject.PDCEmulator
                Credential          = $Credential
                ADobject          = $domainObject
            }
            $script:domains.SID["$($data.SID)"] = $data
            $script:domains.Name[$data.Name] = $data
            $script:domains.FQDN[$data.FQDN] = $data
            $script:domains.NetBIOSName[$data.NetBIOSName] = $data
            foreach ($upn in $data.UPNs)
            {
                if (-not $script:domains.UPN[$upn]) { $script:domains.UPN[$upn] = @() }
                if ($script:domains.UPN[$upn].FQDN -contains $data.FQDN) { continue }
                $script:domains.UPN[$upn] += $data
            }
        }
    }
}

function Resolve-Domain
{
<#
    .SYNOPSIS
        Resolves a domain based on its name.
     
    .DESCRIPTION
        Resolves a domain based on its name.
        Retrieves the information available from Get-ADDomain, but can tune just what it returns.
        Automatically caches results, in order to optimize performance.
     
        Use Clear-DomainCache to clear this cache.
     
    .PARAMETER Name
        Name of the domain to resolve.
        Defaults to the domain of the targeted server (Server parameter).
     
    .PARAMETER OutputType
        What piece of information to return.
        Defaults to the full ADObject of the domain.
     
    .PARAMETER Server
        The server / domain to work with.
     
    .PARAMETER Credential
        The credentials to use for this operation.
     
    .EXAMPLE
        PS C:\> Resolve-Domain
     
        Resolves the current domain.
     
    .EXAMPLE
        PS C:\> Resolve-Domain -Name fabrikam.org -Server dc01.fabrikam.org -Credential $cred
     
        Resolves the domain 'fabrikam.org' using the server 'dc01.fabrikam.org' and the specified credentials.
#>

    [CmdletBinding()]
    param (
        [string]
        $Name,
        
        [ValidateSet('ADObject', 'FQDN', 'Name', 'SID', 'DistinguishedName', 'NetBIOSName', 'DataSet')]
        [string]
        $OutputType = 'ADObject',
        
        [PSFComputer]
        $Server,
        
        [PSCredential]
        $Credential
    )
    
    begin
    {
        $parameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential
        $creds = $PSBoundParameters | ConvertTo-PSFHashtable -Include Credential
        
        if (-not $Name)
        {
            try { $Name = (Get-Domain @parameters).DNSRoot }
            catch { $Name = $env:USERDNSDOMAIN }
        }
        
        #region Utility Functions
        function ConvertTo-Output
        {
            [CmdletBinding()]
            param (
                [string]
                $OutputType,
                
                [Parameter(ValueFromPipeline = $true)]
                $InputObject
            )
            
            process
            {
                foreach ($item in $InputObject)
                {
                    switch ($OutputType)
                    {
                        'ADObject' { $item.ADObject }
                        'FQDN' { $item.FQDN }
                        'Name' { $item.Name }
                        'SID' { $item.SID }
                        'DistinguishedName' { $item.DistinguishedName }
                        'NetBIOSName' { $item.NetBIOSName }
                        'DataSet' { $item }
                    }
                }
            }
        }
        #endregion Utility Functions
    }
    process
    {
        if ($Name -as [System.Security.Principal.SecurityIdentifier])
        {
            $Name = ([System.Security.Principal.SecurityIdentifier]$Name).AccountDomainSid.Value
            if ($script:domains.SID[$Name]) { return $script:domains.SID[$Name] | ConvertTo-Output -OutputType $OutputType }
        }
        if ($script:domains.FQDN[$Name]) { return $script:domains.FQDN[$Name] | ConvertTo-Output -OutputType $OutputType }
        if ($script:domains.Name[$Name]) { return $script:domains.Name[$Name] | ConvertTo-Output -OutputType $OutputType }
        if ($script:domains.NetBIOSName[$Name]) { return $script:domains.NetBIOSName[$Name] | ConvertTo-Output -OutputType $OutputType }
        
        try
        {
            $domainObject = Get-ADDomain @parameters -Identity $Name -ErrorAction Stop
            Register-Domain -Server $domainObject.DNSRoot @creds
        }
        catch
        {
            if (-not $domainObject)
            {
                try
                {
                    $domainObject = Get-ADDomain -Identity $Name -ErrorAction Stop
                    Register-Domain -Server $domainObject.DNSRoot
                }
                catch { $PSCmdlet.ThrowTerminatingError($_) }
            }
            if (-not $domainObject) { $PSCmdlet.ThrowTerminatingError($_) }
        }
        if (-not $domainObject) { return }
        
        $script:domains.FQDN[$domainObject.DNSRoot] | ConvertTo-Output -OutputType $OutputType
    }
}

function Resolve-Principal
{
<#
    .SYNOPSIS
        Resolves the principals specified.
     
    .DESCRIPTION
        Resolves the principals specified.
     
        This command can accept a variety of inputs and resolve them into its identity.
        Using registered / cached domains, this resolution will try to automatically determine the correct domain to scan and resolve the identity.
        Then this information can be provided in multiple formats, as would be useful for the user.
     
    .PARAMETER Name
        The name to resolve.
        This can be any of the following formats:
        - SamAccountName (will resolve against targeted server/domain)
        - SID
        - UserPrincipalName (Domain may need to be pre-registered, when using a UPN-Suffix that is not equal to the domain's DNS name)
        - NT Account (May encounter issues if multiple domains share the same NetBIOS Name)
     
    .PARAMETER OutputType
        How the output should be formatted:
        ADObject: Return the AD object of the principal
        NTAccount: Return an NT Account object (e.g: 'contoso\max.mustermann')
        SID: Return the SecurityIdentifier uniquele representing the identity. It is generally a good idea to use this, if you want to compare identities.
        DataSet: Return the full dataset contained, including the user AD object and the domain information of the hosting domain.
        UPN: Return the UserPrincipalName
        SamAccountName: Return the SAMAccountName
     
    .PARAMETER Server
        The server / domain to work with.
     
    .PARAMETER Credential
        The credentials to use for this operation.
     
    .EXAMPLE
        PS C:\> Resolve-Principal -Name 'mm'
     
        Resolves the user mm against the local domain.
     
    .EXAMPLE
        PS C:\> Resolve-Principal -Name 'contoso\maria'
     
        Resolves the user maria against the contoso domain.
     
    .EXAMPLE
        PS C:\> Resolve-Principal -Name 'murat@fabrikam.org'
     
        Resolves the user murat against all known domains that support the UPN suffix fabrikam.org.
        Only a domain with the DNS name of fabrikam.org will be detected if not pre-registered or previously already discovered.
     
    .EXAMPLE
        PS C:\> Resolve-Principal -Name 'S-1-5-21-584015949-955715703-1113067636-1105'
     
        Resolves the user with the RID 1105 against the domain with the domain sid 'S-1-5-21-584015949-955715703-1113067636'
#>

    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingEmptyCatchBlock", "")]
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [string]
        $Name,
        
        [ValidateSet('ADObject', 'NTAccount', 'SID', 'DataSet', 'UPN', 'SamAccountName')]
        [string]
        $OutputType = 'ADObject',
        
        [PSFComputer]
        $Server,
        
        [PSCredential]
        $Credential
    )
    
    begin
    {
        $parameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential
        
        $principalProperties = 'ObjectSID', 'SamAccountName', 'UserPrincipalName', 'Name', 'ObjectClass'
        
        #region Utility functions
        function Convert-ADPrincipal
        {
            [CmdletBinding()]
            param (
                $DomainInfo,
                
                [Parameter(ValueFromPipeline = $true)]
                $ADObject
            )
            
            process
            {
                foreach ($inputItem in $ADObject)
                {
                    $data = [pscustomobject]@{
                        SID = $inputItem.ObjectSID
                        SamAccountName = $inputItem.SamAccountName
                        UserPrincipalName = $inputItem.UserPrincipalName
                        Name = $inputItem.Name
                        ObjectClass = $inputItem.ObjectClass
                        Domain = $DomainInfo
                        ADObject = $inputItem
                    }
                    $script:principals.SID["$($inputItem.ObjectSID)"] = $data
                    if ($inputItem.UserPrincipalName) { $script:principals.UserPrincipalName[$inputItem.UserPrincipalName] = $data }
                    $script:principals.NTAccount[('{0}\{1}' -f $DomainInfo.NetBIOSName, $inputItem.SamAccountName)] = $data
                    
                    if (-not $script:principals.Domains[$DomainInfo.FQDN])
                    {
                        $script:principals.Domains[$DomainInfo.FQDN] = @{ }
                    }
                    $script:principals.Domains[$DomainInfo.FQDN][$data.SamAccountName] = $data
                    
                    $data
                }
            }
        }
        
        function ConvertTo-Output
        {
            [CmdletBinding()]
            param (
                [string]
                $OutputType,
                
                [Parameter(ValueFromPipeline = $true)]
                $InputObject
            )
            
            process
            {
                foreach ($item in $InputObject)
                {
                    switch ($OutputType)
                    {
                        'ADObject' { $item.ADObject }
                        'NTAccount' { ('{0}\{1}' -f $item.Domain.NetBIOSName, $item.SamAccountName) -as [System.Security.Principal.NTAccount] }
                        'SID' { $item.SID }
                        'DataSet' { $item }
                        'UPN' { $item.UserPrincipalName }
                        'SamAccountName' { $item.SamAccountName }
                    }
                }
            }
        }
        
        function Get-DomainInfo
        {
            [CmdletBinding()]
            param (
                [string]
                $Name,
                
                [Hashtable]
                $Parameters
            )
            
            $data = [pscustomobject]@{
                UserName = $Name
                Domain   = $Null
                Type     = 'Default'
            }
            
            #region Name notation Cases - resolve domain name and username
            try { $domainName = (Get-Domain @Parameters).DNSRoot }
            catch { $domainName = $env:USERDNSDOMAIN }
            if ($Name -like '*@*')
            {
                $data.UserName = @($Name -split '@')[0]
                $data.Type = 'UPN'
                $domainName = @($Name -split '@')[-1]
            }
            elseif ($Name -like '*\*')
            {
                $data.UserName = @($Name -split '\\')[-1]
                $domainName = @($Name -split '\\')[0]
            }
            elseif ($Name -as [System.Security.Principal.SecurityIdentifier])
            {
                $data.UserName = $Name
                $data.Type = 'SID'
                if (($Name -as [System.Security.Principal.SecurityIdentifier]).AccountDomainSid) { $domainName = $Name }
            }
            #endregion Name notation Cases - resolve domain name and username
            
            if ($data.Type -eq 'UPN' -and $script:domains.UPN[$domainName])
            {
                $data.Domain = $script:domains.UPN[$domainName]
                return $data
            }
            
            try { $domainObject = Resolve-Domain -Name $domainName -OutputType DataSet @Parameters }
            catch { }
            if ($domainObject)
            {
                $data.Domain = $domainObject
                return $data
            }
            
            # Didn't find anything and not a UPN? Return nothing
            if ($Name -notlike '*@*') { return }
            
            # UPN Suffix Resolution
            $domains = $script:domains.UPN[$domainName]
            
            if (-not $domains) { return }
            
            $data.Domain = $domains
            $data
        }
        
        function Get-ADObject2
        {
            [CmdletBinding()]
            param (
                $DomainInfoObject,
                
                [string]
                $LdapFilter,
                
                [string[]]
                $Properties,
                
                [System.Collections.Hashtable]
                $Parameters
            )
            
            Write-PSFMessage -Level Debug -String 'Resolve-Principal.Resolving.Query' -StringValues $LdapFilter -FunctionName 'Resolve-Principal'
            $adObject = $null
            
            foreach ($domainInfo in $DomainInfoObject)
            {
                $paramClone = $Parameters.Clone()
                $paramClone += @{
                    LDAPFilter = $LdapFilter
                    ErrorAction = 'Stop'
                    Properties = $Properties
                }
                $paramClone.Server = $domainInfo.FQDN
                
                try { $adObject = Get-ADObject @paramClone }
                catch
                {
                    $paramClone.Remove('Credential')
                    if ($domainInfo.Credential) { $paramClone.Credential = $domainInfo.Credential }
                    
                    try { $adObject = Get-ADObject @paramClone }
                    catch { Write-PSFMessage -Level Warning -String 'Resolve-Principal.AccessError' -StringValues $domainInfo.FQDN -ErrorRecord $_ -FunctionName 'Resolve-Principal' }
                }
                
                if ($adObject) { return $adObject }
            }
        }
        #endregion Utility functions
    }
    process
    {
        if ($script:principals.SID[$Name]) { return $script:principals.SID[$Name] | ConvertTo-Output -OutputType $OutputType }
        if ($script:principals.UserPrincipalName[$Name]) { return $script:principals.UserPrincipalName[$Name] | ConvertTo-Output -OutputType $OutputType }
        if ($script:principals.NTAccount[$Name]) { return $script:principals.NTAccount[$Name] | ConvertTo-Output -OutputType $OutputType }
        
        if (-not ($Name -as [System.Security.Principal.SecurityIdentifier]))
        {
            try { $Name = ([System.Security.Principal.NTAccount]$Name).Translate([System.Security.Principal.SecurityIdentifier]) }
            catch { }
        }
        
        if ($OutputType -eq 'SID' -and $Name -as [System.Security.Principal.SecurityIdentifier])
        {
            return $Name -as [System.Security.Principal.SecurityIdentifier]
        }
        
        $domainInfo = Get-DomainInfo -Name $Name -Parameters $parameters
        if (-not $domainInfo)
        {
            Write-PSFMessage -Level Warning -String 'Resolve-Principal.Resolve.Domain.Error' -StringValues $Name
            Write-Error "Unable to resolve domain for $Name"
            return
        }
        
        switch ($domainInfo.Type)
        {
            #region UPN Based Resolution
            'UPN'
            {
                $adObject = $null
                $adObject = Get-ADObject2 -DomainInfoObject $domainInfo.Domain -LdapFilter "(userPrincipalName=$Name)" -Properties $principalProperties -Parameters $parameters
                
                if (-not $adObject)
                {
                    Write-PSFMessage -Level Warning -String 'Resolve-Principal.Resolve.Principal.Error' -StringValues $Name
                    Write-Error "Unable to resolve principal $Name"
                    return
                }
                $adObject | Convert-ADPrincipal -DomainInfo $domainInfo | ConvertTo-Output -OutputType $OutputType
            }
            #endregion UPN Based Resolution
            
            #region SID Based Resolution
            'SID'
            {
                $adObject = $null
                $adObject = Get-ADObject2 -DomainInfoObject $domainInfo.Domain -LdapFilter "(objectSID=$($domainInfo.UserName))" -Properties $principalProperties -Parameters $parameters
                
                if (-not $adObject)
                {
                    Write-PSFMessage -Level Warning -String 'Resolve-Principal.Resolve.Principal.Error' -StringValues $Name
                    Write-Error "Unable to resolve principal $Name"
                    return
                }
                $adObject | Convert-ADPrincipal -DomainInfo $domainInfo.Domain | ConvertTo-Output -OutputType $OutputType
            }
            #endregion SID Based Resolution
            
            #region Default Workflow
            default
            {
                if ($script:principals.Domains[$domainInfo.Domain.FQDN].SamAccountName.$($domainInfo.UserName))
                {
                    return $script:principals.Domains[$domainInfo.Domain.FQDN].SamAccountName.$($domainInfo.UserName) | ConvertTo-Output -OutputType $OutputType
                }
                
                $adObject = $null
                $adObject = Get-ADObject2 -DomainInfoObject $domainInfo.Domain -LdapFilter "(samAccountName=$($domainInfo.UserName))" -Properties $principalProperties -Parameters $parameters
                
                if (-not $adObject)
                {
                    Write-PSFMessage -Level Warning -String 'Resolve-Principal.Resolve.Principal.Error' -StringValues $Name
                    Write-Error "Unable to resolve principal $Name"
                    return
                }
                $adObject | Convert-ADPrincipal -DomainInfo $domainInfo.Domain | ConvertTo-Output -OutputType $OutputType
            }
            #endregion Default Workflow
        }
    }
}


<#
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 'Principal' -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 'Principal' -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 'Principal' -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."

<#
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 'Principal.ScriptBlockName' -Scriptblock {
     
}
#>


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


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


New-PSFLicense -Product 'Principal' -Manufacturer 'Friedrich Weinmann' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2020-06-08") -Text @"
Copyright (c) 2020 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.
"@


<#
SID: <data>
Name: <data>
FQDN: <data>
NetBIOSName: <data>
UPN: @(<data>,<data>,...)
 
<data>:
- DistinguishedName
- Name
- FQDN
- SID
- NetBIOSName
- PDCEmulator
- Credential
- UPNs
- ADObject
#>

$script:domains = @{
    SID = @{ }
    Name = @{ }
    FQDN = @{ }
    NetBIOSName = @{ }
    UPN = @{ }
}


<#
@domain:
- SamAccountName: <data>
 
SID: <data>
UserPrincipalName: <data>
NTAccount: <data>
Domains: @domain
 
<data>:
- SID
- SamAccountName
- UserPrincipalName
- Name
- ObjectClass
- Domain
- ADObject
#>

$script:principals = @{
    SID = @{ }
    UserPrincipalName = @{ }
    NTAccount = @{ }
    Domains = @{ }
}


<#
Plain domain cache for asking for a specific domain object.
Caches based on Server parameter.
#>

$script:domain_cache = @{
    
}
#endregion Load compiled code