ADMF.Core.psm1
$script:ModuleRoot = $PSScriptRoot $script:ModuleVersion = (Import-PowerShellDataFile -Path "$($script:ModuleRoot)\ADMF.Core.psd1").ModuleVersion # Detect whether at some level dotsourcing was enforced $script:doDotSource = Get-PSFConfigValue -FullName ADMF.Core.Import.DoDotSource -Fallback $false if ($ADMFCore_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 ADMF.Core.Import.IndividualFiles -Fallback $false if ($ADMFCore_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 'ADMF.Core' -Language 'en-US' function Get-ADIdentifierType { <# .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 .EXAMPLE PS C:\> Get-ADIdentifierType -Name '92469e61-8005-4c6d-b17c-478118f66c20' Validates that the specified string is a GUID. #> [OutputType([string])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $Name ) 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})$') { return 'Guid' } if ($Name -like "*=*") { return 'DN' } if ($Name -match '^S-1-5-21-\d{7}-\d{9}-\d{9}-\d+$') { return 'SID' } return "Unknown" } 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 Server The server to contact for this query. .PARAMETER Credential The credentials to use for authenticating this query. .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')] [string] $SearchRoot, [Parameter(ParameterSetName = 'Configuration')] [switch] $Configuration, [switch] $Raw, [ValidateRange(1, 1000)] [int] $PageSize = 1000, [int] $MaxSize, [System.DirectoryServices.SearchScope] $SearchScope = 'Subtree', [string] $Server, [PSCredential] $Credential ) begin { $searcher = [System.DirectoryServices.DirectorySearcher]::new() $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 $searcher.Filter = $LdapFilter foreach ($propertyName in $Property) { $null = $searcher.PropertiesToLoad.Add($propertyName) } Write-PSFMessage -String Get-LdapObject.Searchfilter -StringValues $LdapFilter -Level Debug } process { try { foreach ($ldapobject in $searcher.FindAll()) { if ($Raw) { $ldapobject continue } $resultHash = @{ } foreach ($key in $ldapobject.Properties.Keys) { # Write-Output verwandelt Arrays mit nur einem Wert in nicht-Array Objekt $resultHash[$key] = $ldapobject.Properties[$key] | Write-Output } if ($resultHash.ContainsKey("ObjectClass")) { $resultHash["PSTypeName"] = $resultHash["ObjectClass"] } [pscustomobject]$resultHash } } catch { Stop-PSFFunction -String 'Get-LdapObject.SearchError' -ErrorRecord $_ -Cmdlet $PSCmdlet -EnableException $true } } } 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", "")] [OutputType([System.DirectoryServices.DirectoryEntry])] [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) { [System.DirectoryServices.DirectoryEntry]::new($resolvedPath) } else { $entry = [System.DirectoryServices.DirectoryEntry]::new() [System.DirectoryServices.DirectoryEntry]::new(('LDAP://{0}' -f $entry.distinguishedName[0])) } } else { if ($resolvedPath) { [System.DirectoryServices.DirectoryEntry]::new($resolvedPath, $Credential.UserName, $Credential.GetNetworkCredential().Password) } else { [System.DirectoryServices.DirectoryEntry]::new(("LDAP://DC={0}" -f ($env:USERDNSDOMAIN -split "\." -join ",DC=")), $Credential.UserName, $Credential.GetNetworkCredential().Password) } } } 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 ) begin { #region Defaults $stopDefault = @{ Target = $Object EnableException = $true Cmdlet = $PSCmdlet } #endregion Defaults } 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(), $Object $null = $dstRootDSE.Put("replicateSingleObject", $replicationCommand) Invoke-PSFProtectedCommand -ActionString 'Sync-LdapObject.PerformingReplication' -ActionStringValues $Server, $Target -Target $Object -ScriptBlock { $null = $dstRootDSE.SetInfo() } -EnableException $EnableException -PSCmdlet $PSCmdlet -RetryCount 2 -RetryWait 1 } } function Sync-LdapObjectParallel { <# .SYNOPSIS Start LDAP-based single-object replication in parallel. .DESCRIPTION Start LDAP-based single-object replication. All servers will start sync with the target DC in parallel. Use this to minimize replication latency for critical changes on a single object, such as the krbtgt account. .PARAMETER Object The guid of the object to replicate. .PARAMETER Server The server(s) from which to trigger the replication. .PARAMETER Target The target DC to replicate with. .PARAMETER Throttle Up to how many replications should be triggered in parallel. Defaults to 8 times the CPU count (this action mostly consists on waiting for the network response). .PARAMETER Credential Credentials to use when connecting to the Server(s). No connecting credentials for the target server are necessary, as this is handled by the servers operated against. .PARAMETER Reverse Reverse the sync order. By default, each server is instructed to replicate with the target. By reversing this, the target is instructed to replicate with each server instead. .PARAMETER Configuration Whether the object being replicated is in the configuration partition. .EXAMPLE PS C:\> Sync-LdapObjectParallel -Object 'CN=krbtgt,CN=Users,DC=contoso,DC=com' -Server 'dc2.contoso.com','dc3.contoso.com' -Target 'dc1.contoso.com' Replicates the krbtgt account from dc1 to dc2 & dc3 in parallel. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSReviewUnusedParameter", "")] [CmdletBinding()] param ( [Parameter(Mandatory = $true, Position = 0)] [string] $Object, [Parameter(Mandatory = $true, Position = 1)] [string[]] $Server, [Parameter(Mandatory = $true, Position = 2)] [string] $Target, [int] $Throttle = ($env:NUMBER_OF_PROCESSORS * 8), [PSCredential] $Credential, [switch] $Reverse, [switch] $Configuration ) begin { #region Scriptblock $scriptblock = { param ( $Settings ) & (Get-Module 'ADMF.Core') { try { $null = Sync-LdapObject @Settings [PSCustomObject]@{ PSTypeName = 'ADMF.Core.SyncResult' ComputerName = $Settings.Server Success = $true Object = $Settings.Object Message = "" ExitCode = 0 Error = $null } } catch { [PSCustomObject]@{ PSTypeName = 'ADMF.Core.SyncResult' ComputerName = $Settings.Server Success = $false Object = $Settings.Object Message = "$_" ExitCode = 1 Error = $_ } } } } #endregion Scriptblock $parameters = $PSBoundParameters | ConvertTo-PSFHashtable -Include Object, Target, Configuration, Credential if ($Reverse) { $parameters.Server = $Target } $initialSessionState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault() $initialSessionState.ImportPSModule(("{0}\PSFramework.psd1" -f (Get-Module PSFramework).ModuleBase)) $initialSessionState.ImportPSModule(("{0}\ADMF.Core.psd1" -f (Get-Module 'ADMF.Core').ModuleBase)) $pool = [RunspaceFactory]::CreateRunspacePool($initialSessionState) $null = $pool.SetMinRunspaces(1) $null = $pool.SetMaxRunspaces($Throttle) $pool.ApartmentState = "MTA" $pool.Open() $runspaces = @() } process { foreach ($serverName in $Server) { $tempParameters = $parameters.Clone() if ($Reverse) { $tempParameters.Target = $serverName } else { $tempParameters.Server = $serverName } $runspace = [PowerShell]::Create() $null = $runspace.AddScript($scriptBlock) $null = $runspace.AddArgument($tempParameters) $runspace.RunspacePool = $pool $runspaces += [PSCustomObject]@{ Pipe = $runspace; Status = $runspace.BeginInvoke() } } foreach ($runspace in $runspaces) { $runspace.Pipe.EndInvoke($runspace.Status) $runspace.Pipe.Dispose() } } end { $pool.Close() $pool.Dispose() } } function Clear-AdcConfiguration { <# .SYNOPSIS Resets all configuration settings part of ADMF processing. .DESCRIPTION Resets all configuration settings part of ADMF processing. Hard resets its own configuration data. Offers an extension point via the PSFCallback system that its dependents should tie in for all logic resetting their own configuration settings. Can also be used as an extension point by a management wrapper on top of the ADMF system. To register your own logic, run the following command: Register-PSFCallback -Name MyModule.ConfigurationReset -ModuleName ADMF.Core -CommandName Clear-AdcConfiguration -ScriptBlock $scriptblock (replacing "MyModule" with your module's name and defining the logic in $scriptblock) .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:\> Clear-AdcConfiguration Resets all configuration settings part of ADMF processing. #> [CmdletBinding()] Param ( [switch] $EnableException ) process { Invoke-PSFCallback -PSCmdlet $PSCmdlet -EnableException $EnableException & "$script:ModuleRoot\internal\scripts\variables.ps1" Clear-StringMapping } } function Compare-AdcProperty { <# .SYNOPSIS Helper function simplifying the changes processing of Test-* commands. .DESCRIPTION Helper function simplifying the changes processing of Test-* commands. .PARAMETER Property The property to use for comparison. .PARAMETER Configuration The object that was used to define the desired state. .PARAMETER ADObject The AD Object containing the actual state. .PARAMETER Changes An arraylist where changes get added to. The content of -Property will be added if the comparison fails. .PARAMETER Resolve Whether the value on the configured object's property should be string-resolved. .PARAMETER ADProperty The property on the ad object to use for the comparison. If this parameter is not specified, it uses the value from -Property. .PARAMETER Parameters AD Parameters to pass through for Resolve-String. .PARAMETER AsString Compare properties as string. Will convert all $null values to "". .PARAMETER AsUpdate The result added to the changes arraylist is a custom object with greater details than the default. .PARAMETER CaseSensitive Property comparisons are executed minding casing of values. .PARAMETER IfExists If the property compared does not exist on the configured item, return silently. .PARAMETER Type What kind of component is the compared object part of. Used together with the -AsUpdate parameter to name the resulting object. .EXAMPLE PS C:\> Compare-AdcProperty -Property Description -Configuration $ouDefinition -ADObject $adObject -Changes $changes -Resolve Compares the description on the configuration object (after resolving it) with the one on the ADObject and adds to $changes if they are inequal. #> [CmdletBinding()] Param ( [Parameter(Mandatory = $true)] [string] $Property, [Parameter(Mandatory = $true)] [object] $Configuration, [Parameter(Mandatory = $true)] [object] $ADObject, [Parameter(Mandatory = $true)] [AllowEmptyCollection()] [System.Collections.ArrayList] $Changes, [switch] $Resolve, [string] $ADProperty, [hashtable] $Parameters = @{ }, [switch] $AsString, [switch] $AsUpdate, [switch] $CaseSensitive, [switch] $IfExists, [string] $Type = 'Unknown' ) begin { if (-not $ADProperty) { $ADProperty = $Property } } process { if ($IfExists -and $Configuration.PSObject.Properties.Name -notcontains $Property) { return } $param = @{ Property = $Property Identity = $ADObject.DistinguishedName Type = $Type } $propValue = $Configuration.$Property if ($Resolve) { $propValue = $propValue | Resolve-String @parameters } if (($propValue -is [System.Collections.ICollection]) -and ($ADObject.$ADProperty -is [System.Collections.ICollection])) { if (Compare-Object $propValue $ADObject.$ADProperty -CaseSensitive:$CaseSensitive) { if ($AsUpdate) { $null = $Changes.Add((New-AdcChange @param -NewValue $propValue -OldValue $ADObject.$ADProperty)) } else { $null = $Changes.Add($Property) } } } elseif ($AsString) { if ($CaseSensitive) { $result = "$propValue" -cne "$($ADObject.$ADProperty)" } else { $result = "$propValue" -ne "$($ADObject.$ADProperty)" } if ($result) { if ($AsUpdate) { $null = $Changes.Add((New-AdcChange @param -NewValue "$propValue" -OldValue "$($ADObject.$ADProperty)")) } else { $null = $Changes.Add($Property) } } } else { if ($CaseSensitive) { $result = $propValue -cne $ADObject.$ADProperty } else { $result = $propValue -ne $ADObject.$ADProperty } if ($result) { if ($AsUpdate) { $null = $Changes.Add((New-AdcChange @param -NewValue $propValue -OldValue $ADObject.$ADProperty)) } else { $null = $Changes.Add($Property) } } } } } function Get-AdcExchangeVersion { <# .SYNOPSIS Return Exchange Version Information. .DESCRIPTION Return Exchange Version Information. .PARAMETER Binding The Binding to use. .PARAMETER Name The name to filter by. .EXAMPLE PS C:\> Get-AdcExchangeVersion Return a list of all Exchange Versions #> [CmdletBinding()] param ( [PsfArgumentCompleter('ADMF.Core.ExchangeVersion')] [string] $Binding, [string] $Name = '*' ) begin { $selectAliases = @( 'SchemaVersion as RangeUpper' 'ConfigurationVersion as ObjectVersionConfig' 'DomainVersion as ObjectVersionDomain' ) } process { if ($Binding) { return $script:exchangeVersionMapping[$Binding] | Select-PSFObject -KeepInputObject -Alias $selectAliases -TypeName 'ADMF.Core.ExchangeVersion' } $script:exchangeVersionMapping.Values | Where-Object Name -Like $Name | Sort-Object @( { $_.Name -replace '^Exchange (\d+).+$','$1'} 'SchemaVersion' 'ConfigurationVersion' 'DomainVersion' { $_.Name -replace '^.+?(\d+)$','$1' -as [int] } 'Name' ) | Select-PSFObject -KeepInputObject -Alias $selectAliases -TypeName 'ADMF.Core.ExchangeVersion' } } function New-AdcChange { <# .SYNOPSIS Create a new change object. .DESCRIPTION Create a new change object. Used for test results in cases where no specialized change objects are intended. Mostly used from the internal Compare-Property command. .PARAMETER Property The property being updated .PARAMETER OldValue The previous value the property had .PARAMETER NewValue The new value the property should receive .PARAMETER Identity Identity of the object being updated .PARAMETER Type The object/component type of the object being changed .EXAMPLE PS C:\> New-Change -Property Path -OldValue $adObject.DistinguishedName -NewValue $path -Identity $adObject -Type Object Creates a new change object for the path of an object #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $Property, $OldValue, $NewValue, [string] $Identity, [string] $Type = 'Unknown' ) $change = [PSCustomObject]@{ PSTypeName = "DomainManagement.$Type.Change" Property = $Property Old = $OldValue New = $NewValue Identity = $Identity } Add-Member -InputObject $change -MemberType ScriptMethod -Name ToString -Value { '{0} -> {1}' -f $this.Property, $this.New } -Force -PassThru } function Sync-AdcObject { <# .SYNOPSIS Replicate a single item between DCs. .DESCRIPTION Replicate a single item between DCs. Can use either WinRM or LDAP to trigger a bulk sync of a single object in parallel. Use this command to ensure a specific object in AD has been replicated across all targeted DCs. .PARAMETER Object The object to replicate. Must be a distinguishedName. .PARAMETER Source The server that contains the current state of the targeted object. .PARAMETER Target The server(s) that should receive the latest updates for the targeted object. .PARAMETER Credential Credentials tro use for authenticating the operation. .PARAMETER Type Which protocl should be used to trigger the replication. Can use either LDAP or WinRM, defaults to LDAP. .PARAMETER Reverse Reverses the replication order in an LDAP-based replication task. In this case, rather than fanning out network connections, the source server is ordered to replicate with each specified target server. .EXAMPLE PS C:\> Sync-AdcObject -Object $userAccount -Source $pdc -Target (Get-ADComputer -LdapFilter "(&(primaryGroupID=516)(!(name=$pdc)))").DNSHostName Replicates the AD object stored in $userAccount across all domain controllers in the current domain. #> [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $Object, [Parameter(Mandatory = $true)] [string] $Source, [Parameter(Mandatory = $true)] [string[]] $Target, [PSCredential] $Credential, [ValidateSet('LDAP','WinRM')] [string] $Type = 'LDAP', [switch] $Reverse ) begin { $credParam = $PSBoundParameters | ConvertTo-PSFHashtable -Include Credential } process { $results = switch ($Type) { #region LDAP-triggered replication 'LDAP' { $adObject = Get-ADObject @credParam -Identity $Object -Server $Source -Properties ObjectGUID Sync-LdapObjectParallel @credParam -Object $adObject.ObjectGUID -Server $Target -Target $Source -Reverse:$Reverse } #endregion LDAP-triggered replication #region WinRM-triggered replication 'WinRM' { Invoke-PSFCommand @credParam -ComputerName $Target -ScriptBlock { param ( $TargetDC, $ADObject ) $message = repadmin.exe /replsingleobj $env:COMPUTERNAME $TargetDC $ADObject *>&1 $result = 0 -eq $LASTEXITCODE [PSCustomObject]@{ ComputerName = $env:COMPUTERNAME Success = $result Message = ($message | Where-Object { $_ }) ExitCode = $LASTEXITCODE Error = $null } } -ArgumentList $Source, $Object -ErrorVariable errorVar -ErrorAction SilentlyContinue | Select-PSFObject -KeepInputObject -TypeName 'ADMF.Core.SyncResult' foreach ($errorObject in $errorVar) { if ($errorObject.InvocationInfo.InvocationName -ne 'Invoke-PSFCommand') { continue } Write-PSFMessage -Level Warning -String 'Sync-AdcObject.ConnectError' -StringValues $errorObject.TargetObject -ErrorRecord $errorObject [PSCustomObject]@{ PSTypeName = 'ADMF.Core.SyncResult' ComputerName = $errorObject.TargetObject.ConnectionInfo.ComputerName Success = $false Message = $errorObject.Exception.Message ExitCode = 1 Error = $errorObject } } } #endregion WinRM-triggered replication } [PSCustomObject]@{ Success = $results.Success -notcontains $false SuccessPercent = @($results).Where{ $_.Success }.Count / $Target.Count * 100 Results = $results ServerSuccess = @($results).Where{ $_.Success }.ComputerName ServerFailed = @($results).Where{ -not $_.Success }.ComputerName SuccessCount = ($results | Where-Object Success | Measure-Object).Count } } } <# 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 'ADMF.Core' -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 'ADMF.Core' -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 'ADMF.Core' -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 'ADMF.Core.ScriptBlockName' -Scriptblock { } #> <# # Example: Register-PSFTeppScriptblock -Name "ADMF.Core.alcohol" -ScriptBlock { 'Beer','Mead','Whiskey','Wine','Vodka','Rum (3y)', 'Rum (5y)', 'Rum (7y)' } #> Register-PSFTeppScriptblock -Name 'ADMF.Core.ExchangeVersion' -ScriptBlock { & (Get-Module ADMF.Core) { $script:exchangeVersionMapping.Keys } } <# # Example: Register-PSFTeppArgumentCompleter -Command Get-Alcohol -Parameter Type -Name ADMF.Core.alcohol #> # Variables that should be reset on configuration reload # Useful source: https://eightwone.com/references/schema-versions/ $script:exchangeVersionMapping = @{ '2013RTM' = [PSCustomObject]@{ Name = 'Exchange 2013 RTM'; DomainVersion = 13236; ConfigurationVersion = 15449; SchemaVersion = 15137; Binding = '2013RTM' } '2013CU1' = [PSCustomObject]@{ Name = 'Exchange 2013 CU1'; DomainVersion = 13236; ConfigurationVersion = 15614; SchemaVersion = 15254; Binding = '2013CU1' } '2013CU2' = [PSCustomObject]@{ Name = 'Exchange 2013 CU2'; DomainVersion = 13236; ConfigurationVersion = 15688; SchemaVersion = 15281; Binding = '2013CU2' } '2013CU3' = [PSCustomObject]@{ Name = 'Exchange 2013 CU3'; DomainVersion = 13236; ConfigurationVersion = 15763; SchemaVersion = 15283; Binding = '2013CU3' } '2013SP1' = [PSCustomObject]@{ Name = 'Exchange 2013 SP1'; DomainVersion = 13236; ConfigurationVersion = 15844; SchemaVersion = 15292; Binding = '2013SP1' } '2013CU5' = [PSCustomObject]@{ Name = 'Exchange 2013 CU5'; DomainVersion = 13236; ConfigurationVersion = 15870; SchemaVersion = 15300; Binding = '2013CU5' } '2013CU6' = [PSCustomObject]@{ Name = 'Exchange 2013 CU6'; DomainVersion = 13236; ConfigurationVersion = 15965; SchemaVersion = 15303; Binding = '2013CU6' } '2013CU7' = [PSCustomObject]@{ Name = 'Exchange 2013 CU7'; DomainVersion = 13236; ConfigurationVersion = 15965; SchemaVersion = 15312; Binding = '2013CU7' } '2013CU8' = [PSCustomObject]@{ Name = 'Exchange 2013 CU8'; DomainVersion = 13236; ConfigurationVersion = 15965; SchemaVersion = 15312; Binding = '2013CU8' } '2013CU9' = [PSCustomObject]@{ Name = 'Exchange 2013 CU9'; DomainVersion = 13236; ConfigurationVersion = 15965; SchemaVersion = 15312; Binding = '2013CU9' } '2013CU10' = [PSCustomObject]@{ Name = 'Exchange 2013 CU10'; DomainVersion = 13236; ConfigurationVersion = 16130; SchemaVersion = 15312; Binding = '2013CU10' } '2013CU11' = [PSCustomObject]@{ Name = 'Exchange 2013 CU11'; DomainVersion = 13236; ConfigurationVersion = 16130; SchemaVersion = 15312; Binding = '2013CU11' } '2013CU12' = [PSCustomObject]@{ Name = 'Exchange 2013 CU12'; DomainVersion = 13236; ConfigurationVersion = 16130; SchemaVersion = 15312; Binding = '2013CU12' } '2013CU13' = [PSCustomObject]@{ Name = 'Exchange 2013 CU13'; DomainVersion = 13236; ConfigurationVersion = 16130; SchemaVersion = 15312; Binding = '2013CU13' } '2013CU14' = [PSCustomObject]@{ Name = 'Exchange 2013 CU14'; DomainVersion = 13236; ConfigurationVersion = 16130; SchemaVersion = 15312; Binding = '2013CU14' } '2013CU15' = [PSCustomObject]@{ Name = 'Exchange 2013 CU15'; DomainVersion = 13236; ConfigurationVersion = 16130; SchemaVersion = 15312; Binding = '2013CU15' } '2013CU16' = [PSCustomObject]@{ Name = 'Exchange 2013 CU16'; DomainVersion = 13236; ConfigurationVersion = 16130; SchemaVersion = 15312; Binding = '2013CU16' } '2013CU17' = [PSCustomObject]@{ Name = 'Exchange 2013 CU17'; DomainVersion = 13236; ConfigurationVersion = 16130; SchemaVersion = 15312; Binding = '2013CU17' } '2013CU18' = [PSCustomObject]@{ Name = 'Exchange 2013 CU18'; DomainVersion = 13236; ConfigurationVersion = 16130; SchemaVersion = 15312; Binding = '2013CU18' } '2013CU19' = [PSCustomObject]@{ Name = 'Exchange 2013 CU19'; DomainVersion = 13236; ConfigurationVersion = 16130; SchemaVersion = 15312; Binding = '2013CU19' } '2013CU20' = [PSCustomObject]@{ Name = 'Exchange 2013 CU20'; DomainVersion = 13236; ConfigurationVersion = 16130; SchemaVersion = 15312; Binding = '2013CU20' } '2013CU21' = [PSCustomObject]@{ Name = 'Exchange 2013 CU21'; DomainVersion = 13236; ConfigurationVersion = 16130; SchemaVersion = 15312; Binding = '2013CU21' } '2013CU22' = [PSCustomObject]@{ Name = 'Exchange 2013 CU22'; DomainVersion = 13236; ConfigurationVersion = 16131; SchemaVersion = 15312; Binding = '2013CU22' } '2013CU23' = [PSCustomObject]@{ Name = 'Exchange 2013 CU23'; DomainVersion = 13237; ConfigurationVersion = 16133; SchemaVersion = 15312; Binding = '2013CU23' } '2016Preview' = [PSCustomObject]@{ Name = 'Exchange 2016 Preview'; DomainVersion = 13236; ConfigurationVersion = 16041; SchemaVersion = 15317; Binding = '2016Preview' } '2016RTM' = [PSCustomObject]@{ Name = 'Exchange 2016 RTM'; DomainVersion = 13236; ConfigurationVersion = 16210; SchemaVersion = 15317; Binding = '2016RTM' } '2016CU1' = [PSCustomObject]@{ Name = 'Exchange 2016 CU1'; DomainVersion = 13236; ConfigurationVersion = 16211; SchemaVersion = 15323; Binding = '2016CU1' } '2016CU2' = [PSCustomObject]@{ Name = 'Exchange 2016 CU2'; DomainVersion = 13236; ConfigurationVersion = 16212; SchemaVersion = 15325; Binding = '2016CU2' } '2016CU3' = [PSCustomObject]@{ Name = 'Exchange 2016 CU3'; DomainVersion = 13236; ConfigurationVersion = 16212; SchemaVersion = 15326; Binding = '2016CU3' } '2016CU4' = [PSCustomObject]@{ Name = 'Exchange 2016 CU4'; DomainVersion = 13236; ConfigurationVersion = 16213; SchemaVersion = 15326; Binding = '2016CU4' } '2016CU5' = [PSCustomObject]@{ Name = 'Exchange 2016 CU5'; DomainVersion = 13236; ConfigurationVersion = 16213; SchemaVersion = 15326; Binding = '2016CU5' } '2016CU6' = [PSCustomObject]@{ Name = 'Exchange 2016 CU6'; DomainVersion = 13236; ConfigurationVersion = 16213; SchemaVersion = 15330; Binding = '2016CU6' } '2016CU7' = [PSCustomObject]@{ Name = 'Exchange 2016 CU7'; DomainVersion = 13236; ConfigurationVersion = 16213; SchemaVersion = 15332; Binding = '2016CU7' } '2016CU8' = [PSCustomObject]@{ Name = 'Exchange 2016 CU8'; DomainVersion = 13236; ConfigurationVersion = 16213; SchemaVersion = 15332; Binding = '2016CU8' } '2016CU9' = [PSCustomObject]@{ Name = 'Exchange 2016 CU9'; DomainVersion = 13236; ConfigurationVersion = 16213; SchemaVersion = 15332; Binding = '2016CU9' } '2016CU10' = [PSCustomObject]@{ Name = 'Exchange 2016 CU10'; DomainVersion = 13236; ConfigurationVersion = 16213; SchemaVersion = 15332; Binding = '2016CU10' } '2016CU11' = [PSCustomObject]@{ Name = 'Exchange 2016 CU11'; DomainVersion = 13236; ConfigurationVersion = 16214; SchemaVersion = 15332; Binding = '2016CU11' } '2016CU12' = [PSCustomObject]@{ Name = 'Exchange 2016 CU12'; DomainVersion = 13236; ConfigurationVersion = 16215; SchemaVersion = 15332; Binding = '2016CU12' } '2016CU13' = [PSCustomObject]@{ Name = 'Exchange 2016 CU13'; DomainVersion = 13237; ConfigurationVersion = 16217; SchemaVersion = 15332; Binding = '2016CU13' } '2016CU14' = [PSCustomObject]@{ Name = 'Exchange 2016 CU14'; DomainVersion = 13237; ConfigurationVersion = 16217; SchemaVersion = 15332; Binding = '2016CU14' } '2016CU15' = [PSCustomObject]@{ Name = 'Exchange 2016 CU15'; DomainVersion = 13237; ConfigurationVersion = 16217; SchemaVersion = 15332; Binding = '2016CU15' } '2016CU16' = [PSCustomObject]@{ Name = 'Exchange 2016 CU16'; DomainVersion = 13237; ConfigurationVersion = 16217; SchemaVersion = 15332; Binding = '2016CU16' } '2016CU17' = [PSCustomObject]@{ Name = 'Exchange 2016 CU17'; DomainVersion = 13237; ConfigurationVersion = 16217; SchemaVersion = 15332; Binding = '2016CU17' } '2016CU18' = [PSCustomObject]@{ Name = 'Exchange 2016 CU18'; DomainVersion = 13238; ConfigurationVersion = 16218; SchemaVersion = 15332; Binding = '2016CU18' } '2016CU19' = [PSCustomObject]@{ Name = 'Exchange 2016 CU19'; DomainVersion = 13239; ConfigurationVersion = 16219; SchemaVersion = 15333; Binding = '2016CU19' } '2019Preview' = [PSCustomObject]@{ Name = 'Exchange 2019 Preview'; DomainVersion = 13236; ConfigurationVersion = 16213; SchemaVersion = 15332; Binding = '2019Preview' } '2019RTM' = [PSCustomObject]@{ Name = 'Exchange 2019 RTM'; DomainVersion = 13236; ConfigurationVersion = 16751; SchemaVersion = 17000; Binding = '2019RTM' } '2019CU1' = [PSCustomObject]@{ Name = 'Exchange 2019 CU1'; DomainVersion = 13236; ConfigurationVersion = 16752; SchemaVersion = 17000; Binding = '2019CU1' } '2019CU2' = [PSCustomObject]@{ Name = 'Exchange 2019 CU2'; DomainVersion = 13237; ConfigurationVersion = 16754; SchemaVersion = 17001; Binding = '2019CU2' } '2019CU3' = [PSCustomObject]@{ Name = 'Exchange 2019 CU3'; DomainVersion = 13237; ConfigurationVersion = 16754; SchemaVersion = 17001; Binding = '2019CU3' } '2019CU4' = [PSCustomObject]@{ Name = 'Exchange 2019 CU4'; DomainVersion = 13237; ConfigurationVersion = 16754; SchemaVersion = 17001; Binding = '2019CU4' } '2019CU5' = [PSCustomObject]@{ Name = 'Exchange 2019 CU5'; DomainVersion = 13237; ConfigurationVersion = 16754; SchemaVersion = 17001; Binding = '2019CU5' } '2019CU6' = [PSCustomObject]@{ Name = 'Exchange 2019 CU6'; DomainVersion = 13237; ConfigurationVersion = 16754; SchemaVersion = 17001; Binding = '2019CU6' } '2019CU7' = [PSCustomObject]@{ Name = 'Exchange 2019 CU7'; DomainVersion = 13238; ConfigurationVersion = 16755; SchemaVersion = 17001; Binding = '2019CU7' } '2019CU8' = [PSCustomObject]@{ Name = 'Exchange 2019 CU8'; DomainVersion = 13239; ConfigurationVersion = 16756; SchemaVersion = 17002; Binding = '2019CU8' } '2019CU9' = [PSCustomObject]@{ Name = 'Exchange 2019 CU9'; DomainVersion = 13240; ConfigurationVersion = 16757; SchemaVersion = 17002; Binding = '2019CU9' } '2019CU10' = [PSCustomObject]@{ Name = 'Exchange 2019 CU10'; DomainVersion = 13241; ConfigurationVersion = 16758; SchemaVersion = 17003; Binding = '2019CU10' } '2019CU11' = [PSCustomObject]@{ Name = 'Exchange 2019 CU11'; DomainVersion = 13242; ConfigurationVersion = 16759; SchemaVersion = 17003; Binding = '2019CU11' } } New-PSFLicense -Product 'ADMF.Core' -Manufacturer 'Friedrich Weinmann' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2020-09-10") -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 |