LdapTools.psm1

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

# Detect whether at some level dotsourcing was enforced
$script:doDotSource = Get-PSFConfigValue -FullName LdapTools.Import.DoDotSource -Fallback $false
if ($LdapTools_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 LdapTools.Import.IndividualFiles -Fallback $false
if ($LdapTools_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 'LdapTools' -Language 'en-US'

function New-DirectoryEntry
{
    <#
        .SYNOPSIS
            Generates a new directoryy entry object.
         
        .DESCRIPTION
            Generates a new directoryy entry object.
         
        .PARAMETER Path
            The LDAP path to bind to.
         
        .PARAMETER Server
            The server to connect to.
         
        .PARAMETER Credential
            The credentials to use for the connection.
         
        .EXAMPLE
            PS C:\> New-DirectoryEntry
 
            Creates a directory entry in the default context.
 
        .EXAMPLE
            PS C:\> New-DirectoryEntry -Server dc1.contoso.com -Credential $cred
 
            Creates a directory entry in the default context of the target server.
            The connection is established to just that server using the specified credentials.
    #>

    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
    [CmdletBinding()]
    param (
        [string]
        $Path,
        
        [AllowEmptyString()]
        [string]
        $Server,
        
        [PSCredential]
        [AllowNull()]
        $Credential
    )
    
    if (-not $Path) { $resolvedPath = '' }
    elseif ($Path -like "LDAP://*") { $resolvedPath = $Path }
    elseif ($Path -notlike "*=*") { $resolvedPath = "LDAP://DC={0}" -f ($Path -split "\." -join ",DC=") }
    else { $resolvedPath = "LDAP://$($Path)" }
    
    if ($Server -and ($resolvedPath -notlike "LDAP://$($Server)/*"))
    {
        $resolvedPath = ("LDAP://{0}/{1}" -f $Server, $resolvedPath.Replace("LDAP://", "")).Trim("/")
    }
    
    if (($null -eq $Credential) -or ($Credential -eq [PSCredential]::Empty))
    {
        if ($resolvedPath) { New-Object System.DirectoryServices.DirectoryEntry($resolvedPath) }
        else
        {
            $entry = New-Object System.DirectoryServices.DirectoryEntry
            New-Object System.DirectoryServices.DirectoryEntry(('LDAP://{0}' -f $entry.distinguishedName[0]))
        }
    }
    else
    {
        if ($resolvedPath) { New-Object System.DirectoryServices.DirectoryEntry($resolvedPath, $Credential.UserName, $Credential.GetNetworkCredential().Password) }
        else { New-Object System.DirectoryServices.DirectoryEntry(("LDAP://DC={0}" -f ($env:USERDNSDOMAIN -split "\." -join ",DC=")), $Credential.UserName, $Credential.GetNetworkCredential().Password) }
    }
}

function Resolve-Identity
{
<#
    .SYNOPSIS
        Returns the type of the identifier string offered.
     
    .DESCRIPTION
        Returns the type of the identifier string offered.
        Can differentiate between distinguished names, objectGuid or SID.
        Will not perform any network calls to validate results.
     
    .PARAMETER Name
        The name to resolve
     
    .PARAMETER GetFilterCondition
        Returns a valid ldap filter condition instead of just the type
     
    .PARAMETER AllowSamAccountName
        By default, only DNs, Guids and SIDs are accepted as identifiers.
        All other inputs cause errors.
        By setting this switch, we also allow SamAccountNames as fourth input option.
        This is inherently less precise and should only be used with object types supporting that property.
     
    .EXAMPLE
        PS C:\> Resolve-Identity -Name '92469e61-8005-4c6d-b17c-478118f66c20'
         
        Validates that the specified string is a GUID.
#>

    [OutputType([string])]
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]
        $Name,
        
        [switch]
        $GetFilterCondition,
        
        [switch]
        $AllowSamAccountName
    )
    
    if ($Name -match '^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$') { $type = 'Guid' }
    elseif ($Name -like "*=*") { $type = 'DN' }
    elseif ($Name -match '^S-1-5-21-\d{7}-\d{9}-\d{9}-\d+$') { $type = 'SID' }
    elseif ($AllowSamAccountName) { $type = 'SamAccountName' }
    else { $type = 'Unknown' }
    
    if (-not $GetFilterCondition) { return $type }
    
    switch ($type)
    {
        'SID' { "(objectSID=$($Name))" }
        'Guid'
        {
            $bytes = ([guid]$Name).ToByteArray()
            $segments = foreach ($byte in $bytes)
            {
                "\{0}" -f ([convert]::ToString($byte, 16))
            }
            "(objectGuid=$($segments -join ''))"
        }
        'DN' { "(distinguishedName=$($Name))" }
        default
        {
            if ($AllowSamAccountName) { "(samAccountName=$($Name))" }
            else { throw "Unknown identity type: $Name" }
        }
    }
}

function Disable-LdapAccount {
<#
    .SYNOPSIS
        Disable an active directory account.
     
    .DESCRIPTION
        Disable an active directory account.
     
    .PARAMETER Identity
        Identifier specifying the account to disable.
        Must be either SID, ObjectGuid, SamAccountName or DistinguishedName.
     
    .PARAMETER Server
        The server to contact for this query.
     
    .PARAMETER Credential
        The credentials to use for authenticating this query.
     
    .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:\> Disable-LdapAccount -Identity 'peter'
     
        Disables the account of peter.
#>

    [CmdletBinding(SupportsShouldProcess = $true)]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [string[]]
        $Identity,
        
        [string]
        $Server,
        
        [pscredential]
        $Credential
    )
    begin {
        $parameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential
    }
    
    process {
        foreach ($identityString in $Identity) {
            $filter = Resolve-Identity -Name $identityString -GetFilterCondition -AllowSamAccountName
            if ($identityString -like "*,DC=*") {
                $adAccount = Get-LdapObject @parameters -LdapFilter "(samAccountName=*)" -SearchRoot $identityString -SearchScope Base -Raw -Property UserAccountControl, samAccountName
            }
            else {
                $adAccount = Get-LdapObject @parameters -LdapFilter $filter -Raw -Property UserAccountControl, samAccountName
            }
            
            if (($adAccount.Properties.useraccountcontrol[0] -band 2) -ne 0) {
                Write-PSFMessage -String 'Disable-LdapAccount.AlreadyDisabled' -StringValues $adAccount.Properties.samaccountname[0]
                continue
            }
            
            Invoke-PSFProtectedCommand -ActionString 'Disable-LdapAccount.Disabling' -ActionStringValues $adAccount.Properties.samaccountname[0] -Target $adAccount.Properties.samaccountname[0] -ScriptBlock {
                $accountEntry = $adAccount.GetDirectoryEntry()
                $accountEntry.userAccountControl.value = $accountEntry.userAccountControl.value -bor 2
                $accountEntry.SetInfo()
            } -PSCmdlet $PSCmdlet -EnableException $true -Continue
        }
    }
}

function Enable-LdapAccount {
<#
    .SYNOPSIS
        Enable an active directory account.
     
    .DESCRIPTION
        Enable an active directory account.
     
    .PARAMETER Identity
        Identifier specifying the account to enable.
        Must be either SID, ObjectGuid, SamAccountName or DistinguishedName.
     
    .PARAMETER Server
        The server to contact for this query.
     
    .PARAMETER Credential
        The credentials to use for authenticating this query.
     
    .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:\> Enable-LdapAccount -Identity 'peter'
     
        Enables the account of peter.
#>

    [CmdletBinding(SupportsShouldProcess = $true)]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [string[]]
        $Identity,
        
        [string]
        $Server,
        
        [pscredential]
        $Credential
    )
    begin {
        $parameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential
    }
    
    process {
        foreach ($identityString in $Identity) {
            $filter = Resolve-Identity -Name $identityString -GetFilterCondition -AllowSamAccountName
            if ($identityString -like "*,DC=*") {
                $adAccount = Get-LdapObject @parameters -LdapFilter "(samAccountName=*)" -SearchRoot $identityString -SearchScope Base -Raw -Property UserAccountControl, samAccountName
            }
            else {
                $adAccount = Get-LdapObject @parameters -LdapFilter $filter -Raw -Property UserAccountControl, samAccountName
            }
            
            if (($adAccount.Properties.useraccountcontrol[0] -band 2) -eq 0) {
                Write-PSFMessage -String 'Enable-LdapAccount.AlreadyEnabled' -StringValues $adAccount.Properties.samaccountname[0]
                continue
            }
            
            Invoke-PSFProtectedCommand -ActionString 'Enable-LdapAccount.Enabling' -ActionStringValues $adAccount.Properties.samaccountname[0] -Target $adAccount.Properties.samaccountname[0] -ScriptBlock {
                $accountEntry = $adAccount.GetDirectoryEntry()
                $accountEntry.userAccountControl.value = $accountEntry.userAccountControl.value - ($accountEntry.userAccountControl.value -band 2)
                $accountEntry.SetInfo()
            } -PSCmdlet $PSCmdlet -EnableException $true -Continue
        }
    }
}

function Get-LdapGroup
{
<#
    .SYNOPSIS
        Search active directory for groups.
     
    .DESCRIPTION
        Search active directory for groups.
     
    .PARAMETER Identity
        Unique identity of the group to search.
        Must be either SID, ObjectGuid or DistinguishedName.
     
    .PARAMETER LdapFilter
        The search filter to use when searching for objects.
        Must be a valid LDAP filter.
     
    .PARAMETER Property
        The properties to retrieve.
        Keep bandwidth in mind and only request what is needed.
     
    .PARAMETER SearchRoot
        The root path to search in.
        This generally expects either the distinguished name of the Organizational unit or the DNS name of the domain.
        Alternatively, any legal LDAP protocol address can be specified.
     
    .PARAMETER SearchScope
        Whether to search all OUs beneath the target root, only directly beneath it or only the root itself.
     
    .PARAMETER Server
        The server to contact for this query.
     
    .PARAMETER Credential
        The credentials to use for authenticating this query.
     
    .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-LdapGroup
         
        List all groups in the current domain.
#>

    [CmdletBinding(DefaultParameterSetName = 'Filter')]
    param (
        [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'Identity')]
        [string[]]
        $Identity,
        
        [Parameter(ParameterSetName = 'Filter')]
        [string]
        $LdapFilter = '(samAccountName=*)',
        
        [Alias('Properties')]
        [string[]]
        $Property,
        
        [string]
        $SearchRoot,
        
        [System.DirectoryServices.SearchScope]
        $SearchScope = 'Subtree',
        
        [string]
        $Server,
        
        [PSCredential]
        $Credential,
        
        [switch]
        $EnableException
    )
    
    begin
    {
        # Prepare filter anyway, ignored if using Identity Parameter
        $filter = "(&(objectClass=group)($LdapFilter))"
        
        $defaultProperties = 'DistinguishedName', 'GroupCategory', 'GroupScope', 'Name', 'ObjectClass', 'ObjectGUID', 'SamAccountName', 'ObjectSID'
        $actualProperties = @($defaultProperties) + @($Property | Where-Object { $_ -notin $defaultProperties})
        $parameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include SearchRoot, Server, Credential
        $parameters.SearchScope = $SearchScope
        $parameters.Property = $actualProperties
    }
    process
    {
        foreach ($groupName in $Identity)
        {
            try { $condition = Resolve-Identity -Name $groupName -GetFilterCondition -AllowSamAccountName }
            catch { Stop-PSFFunction -String 'Get-LdapGroup.Identity.BadFormat' -StringValues $groupName -ErrorRecord $_ -EnableException $EnableException -Continue }
            
            Get-LdapObject @parameters -LdapFilter "(&(objectClass=group)$condition)" -TypeName 'Ldap.Group'
        }
        if (-not $Identity)
        {
            Get-LdapObject @parameters -LdapFilter $filter -TypeName 'Ldap.Group'
        }
    }
}

function Get-LdapGroupMember
{
<#
    .SYNOPSIS
        Retrieve the members of a given group.
     
    .DESCRIPTION
        Retrieve the members of a given group.
     
    .PARAMETER Identity
        Identity of the group to get the members of.
        Accepts samaccountname, DN, Guid or SID.
     
    .PARAMETER MemberType
        Only return members of the specified type.
        Values: User, Group or Computer
     
    .PARAMETER Recurse
        Whether to resolve group memberships recursively.
     
    .PARAMETER Property
        Which properties to retrieve from the member objects.
     
    .PARAMETER Server
        The server to contact for this query.
     
    .PARAMETER Credential
        The credentials to use for authenticating this query.
     
    .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-LdapGroupMember "administrators"
     
        Return all members of the administrators group.
#>

    [CmdletBinding()]
    Param (
        [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'Identity')]
        [string[]]
        $Identity,
        
        [ValidateSet('Group','Computer','User')]
        [string[]]
        $MemberType,
        
        [switch]
        $Recurse,
        
        [Alias('Properties')]
        [string[]]
        $Property,
        
        [string]
        $Server,
        
        [PSCredential]
        $Credential,
        
        [switch]
        $EnableException
    )
    
    begin
    {
        #region Prepare AD Operations and filters
        $adParameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential
        
        $typeCondition = ''
        if ($MemberType)
        {
            $conditions = foreach ($type in $MemberType) { "(objectClass=$type)" }
            $typeCondition = '(|{0})' -f ($conditions -join "")
        }
        
        $recurseModifier = ''
        if ($Recurse) { $recurseModifier = ':1.2.840.113556.1.4.1941:' }
        
        $defaultProperties = 'SamAccountName', 'Name', 'DistinguishedName', 'ObjectClass'
        $actualProperties = @($defaultProperties) + @($Property)
        #endregion Prepare AD Operations and filters
    }
    process
    {
        foreach ($groupIdentifier in $Identity)
        {
            try { $condition = Resolve-Identity -Name $groupIdentifier -GetFilterCondition -AllowSamAccountName }
            catch { Stop-PSFFunction -String 'Get-LdapGroupMember.Identity.BadFormat' -StringValues $groupName -ErrorRecord $_ -EnableException $EnableException -Continue }
            
            try { $groupObject = Get-LdapGroup -LdapFilter "(&(objectClass=group)$condition)" @adParameters -EnableException }
            catch { Stop-PSFFunction -String 'Get-LdapGroupMember.Identity.GroupAccessFailure' -StringValues $groupName -ErrorRecord $_ -EnableException $EnableException -Continue }
            
            if (-not $groupObject) { Stop-PSFFunction -String 'Get-LdapGroupMember.Identity.NotFound' -StringValues $groupName -EnableException $EnableException -Continue }
            
            Get-LdapObject @adParameters -LdapFilter "(&(memberof$($recurseModifier)=$($groupObject.DistinguishedName))$($typeCondition))" -Property $actualProperties -TypeName Ldap.GroupMember -AddProperty @{
                Group = $groupObject.SamAccountName
                GroupDN = $groupObject.DistinguishedName
            }
        }
    }
}

function Get-LdapObject {
    <#
        .SYNOPSIS
            Use LDAP to search in Active Directory
 
        .DESCRIPTION
            Utilizes LDAP to perform swift and efficient LDAP Queries.
 
        .PARAMETER LdapFilter
            The search filter to use when searching for objects.
            Must be a valid LDAP filter.
 
        .PARAMETER Property
            The properties to retrieve.
            Keep bandwidth in mind and only request what is needed.
 
        .PARAMETER SearchRoot
            The root path to search in.
            This generally expects either the distinguished name of the Organizational unit or the DNS name of the domain.
            Alternatively, any legal LDAP protocol address can be specified.
 
        .PARAMETER Configuration
            Rather than searching in a specified path, switch to the configuration naming context.
 
        .PARAMETER Raw
            Return the raw AD object without processing it for PowerShell convenience.
 
        .PARAMETER PageSize
            Rather than searching in a specified path, switch to the schema naming context.
 
        .PARAMETER MaxSize
            The maximum number of items to return.
 
        .PARAMETER SearchScope
            Whether to search all OUs beneath the target root, only directly beneath it or only the root itself.
     
        .PARAMETER AddProperty
            Add additional properties to the output object.
            Use to optimize performance, avoiding needing to use Add-Member.
 
        .PARAMETER Server
            The server to contact for this query.
 
        .PARAMETER Credential
            The credentials to use for authenticating this query.
     
        .PARAMETER TypeName
            The name to give the output object
 
        .EXAMPLE
            PS C:\> Get-LdapObject -LdapFilter '(PrimaryGroupID=516)'
             
            Searches for all objects with primary group ID 516 (hint: Domain Controllers).
    #>

    [Alias('ldap')]
    [CmdletBinding(DefaultParameterSetName = 'SearchRoot')]
    param (
        [Parameter(Mandatory = $true, Position = 0)]
        [string]
        $LdapFilter,
        
        [Alias('Properties')]
        [string[]]
        $Property = "*",
        
        [Parameter(ParameterSetName = 'SearchRoot')]
        [Alias('SearchBase')]
        [string]
        $SearchRoot,
        
        [Parameter(ParameterSetName = 'Configuration')]
        [switch]
        $Configuration,
        
        [switch]
        $Raw,
        
        [ValidateRange(1, 1000)]
        [int]
        $PageSize = 1000,
        
        [Alias('SizeLimit')]
        [int]
        $MaxSize,
        
        [System.DirectoryServices.SearchScope]
        $SearchScope = 'Subtree',
        
        [System.Collections.Hashtable]
        $AddProperty,
        
        [string]
        $Server,
        
        [PSCredential]
        $Credential,
        
        [Parameter(DontShow = $true)]
        [string]
        $TypeName
    )
    
    begin {
        #region Utility Functions
        function Get-PropertyName {
            [OutputType([string])]
            [CmdletBinding()]
            param (
                [string]
                $Key,
                
                [string[]]
                $Property
            )
            
            if ($hit = @($Property).Where{ $_ -eq $Key }) { return $hit[0] }
            if ($Key -eq 'ObjectClass') { return 'ObjectClass' }
            if ($Key -eq 'ObjectGuid') { return 'ObjectGuid' }
            if ($Key -eq 'ObjectSID') { return 'ObjectSID' }
            if ($Key -eq 'DistinguishedName') { return 'DistinguishedName' }
            if ($Key -eq 'SamAccountName') { return 'SamAccountName' }
            $script:culture.TextInfo.ToTitleCase($Key)
        }
        #endregion Utility Functions
        
        #region Prepare Searcher
        $searcher = New-Object system.directoryservices.directorysearcher
        $searcher.PageSize = $PageSize
        $searcher.SearchScope = $SearchScope
        
        if ($MaxSize -gt 0) {
            $Searcher.SizeLimit = $MaxSize
        }
        
        if ($SearchRoot) {
            $searcher.SearchRoot = New-DirectoryEntry -Path $SearchRoot -Server $Server -Credential $Credential
        }
        else {
            $searcher.SearchRoot = New-DirectoryEntry -Server $Server -Credential $Credential
        }
        if ($Configuration) {
            $searcher.SearchRoot = New-DirectoryEntry -Path ("LDAP://CN=Configuration,{0}" -f $searcher.SearchRoot.distinguishedName[0]) -Server $Server -Credential $Credential
        }
        
        Write-PSFMessage -String Get-LdapObject.SearchRoot -StringValues $SearchScope, $searcher.SearchRoot.Path -Level Debug
        
        if (Test-PSFParameterBinding -ParameterName Credential) {
            $searcher.SearchRoot = New-Object System.DirectoryServices.DirectoryEntry($searcher.SearchRoot.Path, $Credential.UserName, $Credential.GetNetworkCredential().Password)
        }
        
        $searcher.Filter = $LdapFilter
        
        foreach ($propertyName in $Property) {
            $null = $searcher.PropertiesToLoad.Add($propertyName)
        }
        
        Write-PSFMessage -String Get-LdapObject.Searchfilter -StringValues $LdapFilter -Level Debug
        #endregion Prepare Searcher
    }
    process {
        try {
            foreach ($ldapobject in $searcher.FindAll()) {
                if ($Raw) {
                    $ldapobject
                    continue
                }
                #region Process/Refine Output Object
                $resultHash = @{ }
                foreach ($key in $ldapobject.Properties.Keys) {
                    $resultHash[(Get-PropertyName -Key $key -Property $Property)] = switch ($key) {
                        'ObjectClass' { $ldapobject.Properties[$key][@($ldapobject.Properties[$key]).Count - 1] }
                        'ObjectGuid' { [guid]::new(([byte[]]($ldapobject.Properties[$key] | Write-Output))) }
                        'ObjectSID' { [System.Security.Principal.SecurityIdentifier]::new(([byte[]]($ldapobject.Properties[$key] | Write-Output)), 0) }
                        
                        default { $ldapobject.Properties[$key] | Write-Output }
                    }
                }
                if ($resultHash.ContainsKey("ObjectClass")) { $resultHash["PSTypeName"] = $resultHash["ObjectClass"] }
                if ($TypeName) { $resultHash["PSTypeName"] = $TypeName }
                if ($AddProperty) { $resultHash += $AddProperty }
                $item = [pscustomobject]$resultHash
                Add-Member -InputObject $item -MemberType ScriptMethod -Name ToString -Value {
                    if ($this.DistinguishedName) { $this.DistinguishedName }
                    else { $this.AdsPath }
                } -Force -PassThru
                #endregion Process/Refine Output Object
            }
        }
        catch {
            Stop-PSFFunction -String 'Get-LdapObject.SearchError' -ErrorRecord $_ -Cmdlet $PSCmdlet -EnableException $true
        }
    }
}

function Set-LdapAccountPassword {
<#
    .SYNOPSIS
        Sets the password of an active directory account.
     
    .DESCRIPTION
        Sets the password of an active directory account.
     
    .PARAMETER Identity
        Identifier specifying the account to set the password for.
        Must be either SID, ObjectGuid, SamAccountName or DistinguishedName.
     
    .PARAMETER Password
        The Password to apply to the account specified
     
    .PARAMETER Server
        The server to contact for this query.
     
    .PARAMETER Credential
        The credentials to use for authenticating this query.
     
    .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:\> Set-LdapAccountPassword -Identity 'peter' -Password (Read-Host -AsSecureString)
     
        Sets the password of peter.
#>

    [CmdletBinding(SupportsShouldProcess = $true)]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [string[]]
        $Identity,
        
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [securestring]
        $Password,
        
        [string]
        $Server,
        
        [pscredential]
        $Credential
    )
    begin {
        $parameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential
    }
    
    process {
        foreach ($identityString in $Identity) {
            $filter = Resolve-Identity -Name $identityString -GetFilterCondition -AllowSamAccountName
            if ($identityString -like "*,DC=*") {
                $adAccount = Get-LdapObject @parameters -LdapFilter "(samAccountName=*)" -SearchRoot $identityString -SearchScope Base -Raw -Property UserAccountControl, samAccountName
            }
            else {
                $adAccount = Get-LdapObject @parameters -LdapFilter $filter -Raw -Property UserAccountControl, samAccountName
            }
            
            Invoke-PSFProtectedCommand -ActionString 'Set-LdapAccountPassword.Resetting' -ActionStringValues $adAccount.Properties.samaccountname[0] -Target $adAccount.Properties.samaccountname[0] -ScriptBlock {
                $accountEntry = $adAccount.GetDirectoryEntry()
                $cred = [PSCredential]::new("whatever", $Password)
                $accountEntry.SetPassword($cred.GetNetworkCredential().Password)
                $accountEntry.SetInfo()
            } -PSCmdlet $PSCmdlet -EnableException $true -Continue
        }
    }
}

function Sync-LdapObject
{
    <#
        .SYNOPSIS
            Performs single object replication of an object between two separate directory servers.
         
        .DESCRIPTION
            Performs single object replication of an object between two separate directory servers.
             
        .PARAMETER Object
            The object to replicate.
            Accepts valid system identifiers:
            - SID
            - ObjectGUID
            - DistinguishedName
         
        .PARAMETER Server
            The server from which to replicate.
         
        .PARAMETER Target
            The destination server to replicate to.
         
        .PARAMETER Credential
            The credentials to use for replication.
         
        .PARAMETER Configuration
            If the target object is stored in the configuration node, specifying this parameter is required.
         
        .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:\> Sync-LdapObject -Object '92469e61-8005-4c6d-b17c-478118f66c20' -Server dc1.contoso.com -Target dc2.contoso.com
 
            Synchronizes the object identified by the specified guid from dc1 to dc2.
    #>

    [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Low')]
    param (
        [Parameter(Mandatory = $true, Position = 0)]
        [string]
        $Object,
        
        [Parameter(Mandatory = $true, Position = 1)]
        [string]
        $Server,
        
        [Parameter(Mandatory = $true, Position = 2)]
        [string]
        $Target,
        
        [PSCredential]
        $Credential,
        
        [switch]
        $Configuration
    )
    
    begin
    {
        #region Defaults
        $stopDefault = @{
            Target            = $Object
            EnableException = $true
            Cmdlet            = $PSCmdlet
        }
        #endregion Defaults
        
        #region Resolving target object
        $adParameter = $PSBoundParameters | ConvertTo-PSFHashtable -Include Server, Credential
        switch (Resolve-Identity -Name $Object)
        {
            'SID' { $ldapFilter = "(objectSID=$($Object))" }
            'Guid'
            {
                $bytes = ([guid]$Object).ToByteArray()
                $segments = foreach ($byte in $bytes)
                {
                    "\{0}" -f ([convert]::ToString($byte, 16))
                }
                $ldapFilter = "(objectGuid=$($segments -join ''))"
            }
            'DN' { $ldapFilter = "(distinguishedName=$($Object))" }
        }
        Write-PSFMessage -String 'Sync-LdapObject.SyncObjectFilter' -StringValues $ldapFilter -Target $Object
        try { $resolvedObject = Get-LdapObject @adParameter -LdapFilter $ldapFilter -Properties ObjectGUID -Configuration:$Configuration -ErrorAction Stop }
        catch { Stop-PSFFunction @stopDefault -String 'Sync-LdapObject.ObjectAccessError' -StringValues $Object, $_ -ErrorRecord $_ -OverrideExceptionMessage }
        if (-not $resolvedObject)
        {
            Stop-PSFFunction @stopDefault -String 'Sync-LdapObject.ObjectNotFound' -StringValues $Object -OverrideExceptionMessage
        }
        $objectGUID = ([guid][byte[]]$resolvedObject.objectGUID).Guid
        #endregion Resolving target object
    }
    process
    {
        try { $dstRootDSE = New-DirectoryEntry -Path "LDAP://$($Target)/RootDSE" -Credential $Credential -ErrorAction Stop }
        catch { Stop-PSFFunction @stopDefault -String 'Sync-LdapObject.DestinationAccessError' -StringValues $Target, $_ -ErrorRecord $_ -OverrideExceptionMessage }
        try { $srcRootDSE = New-DirectoryEntry -Path "LDAP://$($Server)/RootDSE" -Credential $Credential }
        catch { Stop-PSFFunction @stopDefault -String 'Sync-LdapObject.SourceAccessError' -StringValues $Server, $_ -ErrorRecord $_ -OverrideExceptionMessage }
        
        $replicationCommand = '{0}:<GUID={1}>' -f $srcRootDSE.dsServiceName.ToString(), $objectGUID
        
        Write-PSFMessage -String 'Sync-LdapObject.PerformingReplication' -StringValues $Server, $Target -Target $Object
        if (Test-PSFShouldProcess -ActionString 'Sync-LdapObject.PerformingReplication' -ActionStringValues $Server, $Target -Target $Object -PSCmdlet $PSCmdlet)
        {
            $dstRootDSE.Put("replicateSingleObject", $replicationCommand)
            try { $dstRootDSE.SetInfo() }
            catch
            {
                Stop-PSFFunction @stopDefault -String 'Sync-LdapObject.FailedReplication' -StringValues $Object, $Server, $Target, $_ -ErrorRecord $_ -OverrideExceptionMessage
            }
        }
    }
}

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


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


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


# Used in the module for capital-casing properties. Consumed by Get-LdapObject
$script:culture = Get-Culture

New-PSFLicense -Product 'LdapTools' -Manufacturer 'Friedrich Weinmann' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2020-09-17") -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.
"@

#endregion Load compiled code