Find-DuplicateValues.ps1

<#PSScriptInfo
 
.VERSION 2.2
 
.GUID f8866277-cfb2-4608-918d-6c987ddbed80
 
.AUTHOR Aaron Guilmette
 
.COMPANYNAME Microsoft
 
.COPYRIGHT 2021
 
.TAGS
 
.LICENSEURI
 
.PROJECTURI https://www.undocumented-features.com/2016/10/17/finding-duplicate-objects-in-active-directory/
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
.DESCRIPTION
Use this script to find object Active Directory objects with duplicate UPN/SMTP values.
 
.PRIVATEDATA
 
#>


<#
.SYNOPSIS
Find objects with duplicate values across multiple
attributes.
 
Object types searched:
- user
- group
- contact
 
Default Attributes searched:
- userPrincipalName
- mail
 
Exchange Attributes searched:
- proxyAddresses
- targetAddress
 
SIP Attributes searched:
- msRTCSIP-PrimaryUserAddress
 
.PARAMETER Address
Object address expressed as a userPrincipalName or
email address.
 
.PARAMETER Autodetect
Detect which schema classes to query automatically.
 
.PARAMETER Credential
Optionally specify a credential to be used.
 
.PARAMETER IncludeExchange
Include Exchange attributes (must have Active Directory
schema extended for Exchange).
 
.PARAMETER IncludeSIP
Include SIP attributes (must have Active Directory schema
extended for a SIP product, such as Live Communications
Server, Office Communications Server, Lync Server, or
Skype for Business Server).
 
.PARAMETER LDAPStyle
Perform older LDAPFilter style matching (which will include
partial matches.
 
.PARAMETER OutputColor
Specify output color for match highlighting.
 
.EXAMPLE
.\Find-DuplicateValues.ps1 -Credential (Get-Credential) -Address john@contoso.com -IncludeExchange
Prompt for credentials and search all domains in forest for default and Exchange attributes that contain john@contoso.com.
 
.EXAMPLE
.\Find-DuplicateValues.ps1 -Address john@contoso.com -IncludeExchange -IncludeSIP
Search all domains in forest for default, Exchange, and SIP attributes that contain john@contoso.com.
 
.EXAMPLE
.\Find-DuplicateValues.ps1 -Credential $cred -Address john@contoso.com -IncludeSIP
Search all domains in forest for default and SIP attributes using saved credential object $cred.
 
.LINK
https://www.undocumented-features.com/2016/10/17/finding-duplicate-objects-in-active-directory/
 
.NOTES
2021-09-02 - Added testing for Exchange and SIP attributes when forcing -IncludeExchange or
             -IncludeSIP parameters to trap errors related to invalid schema attributes.
2021-09-02 - Updated FormatColor syntax for LDAPStyle parameter
2021-02-15 - Cleaned up filter syntax and formatting.
2021-02-13 - Updated and publisehd to PowerShell Gallery.
2019-04-29 - Update to exclude 'objectClass = computer'
2018-04-16 - Update to search for duplicate x500 patterns.
           - Update to perform better in large environments.
2016-10-26 - Update for $FormatEnumeration parameter.
2016-10-17 - The output now highlights the matching values, making it easier to locate conflicting attributes
             - Detect if schema contains SIP and Exchange attributes
             - Due to an issue with Partial Matching, replaced -LDAPFilter with -Filter parameter.
             The original -LDAPFilter syntax is still available if you want to do partial matching
             via the new -LDAPStyle parameter.
2016-10-01 - Original release.
 
All envrionments perform differently. Please test this code before using it
in production.
 
THIS CODE AND ANY ASSOCIATED INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK OF USE, INABILITY TO USE, OR RESULTS FROM THE USE OF
THIS CODE REMAINS WITH THE USER.
 
Author: Aaron Guilmette
        aaron.guilmette@microsoft.com
#>


[CmdletBinding()]
Param (
    [Parameter(Mandatory = $true, Position = 0, HelpMessage = 'Object address to search for, in the form of user@domain.com')]
    [string]$Address,
    [Parameter(Mandatory = $false, HelpMessage = 'Autodetect schema classes')]
    [switch]$AutoDetect = $true,
    [Parameter(Mandatory = $false, HelpMessage = 'Credential')]
    [object]$Credential,
    [array]$Domains,
    [Parameter(Mandatory = $false, HelpMessage = 'Include Exchange Attributes')]
    [switch]$IncludeExchange,
    [Parameter(Mandatory = $false, HelpMessage = 'Include RTC attributes (Live Communications Server, Office Communications Server, Lync, Skype')]
    [switch]$IncludeSIP,
    [Parameter(Mandatory = $false, HelpMessage = 'Specify output color')]
    [ValidateSet("Black", "DarkBlue", "DarkGreen", "DarkCyan", "DarkRed", "DarkMagenta", "DarkYellow", "Gray", "DarkGray", "Blue", "Green", "Cyan", "Red", "Magenta", "Yellow", "White")]
    [string]$OutputColor = "Cyan",
    [Parameter(Mandatory = $false, HelpMessage = 'LDAP Style--will result in partial matches')]
    [switch]$LDAPStyle,
    [switch]$LargeEnvironment
)

Function FormatColor
{
    param (
        [string]$StringMatch,
        [string]$HighlightColor = $OutputColor
    )
    $line = $_
    if ($line)
    {
        $index = $line.IndexOf($StringMatch, [System.StringComparison]::InvariantCultureIgnoreCase)
        while ($index -ge 0)
        {
            Write-Host $line.Substring(0, $index) -NoNewline
            Write-Host $line.Substring($index, $StringMatch.Length) -NoNewline -ForegroundColor $OutputColor
            $used = $StringMatch.Length + $index
            $remain = $line.Length - $used
            $line = $line.Substring($used, $remain)
            $index = $line.IndexOf($StringMatch, [System.StringComparison]::InvariantCultureIgnoreCase)
        }
    }
    
    Write-Host $line
}

# Check for Active Directory module

If (!(Get-Module ActiveDirectory))
{
    try { Import-Module ActiveDirectory -ea Stop }
    catch
    {
        "Active Directory RSAT not installed. Please install and try again.";
        break
    }
    finally { }
}

If ($AutoDetect)
{
    $schema = [directoryservices.activedirectory.activedirectoryschema]::getcurrentschema()
    $ExchTest = $schema.FindClass("user").OptionalProperties | ? { $_.Name -match "msExchRecipientTypeDetails" }
    $SIPTest = $schema.FindClass("user").OptionalProperties | ? { $_.Name -match "msRTCSIP-PrimaryUserAddress" }
    If ($ExchTest) { $IncludeExchange = $true; Write-Host "Found Exchange Attributes." }
    If ($SIPTest) { $IncludeSIP = $true; Write-Host "Found SIP Attributes." }
}

If (!$Domains) { [array]$Forests = (Get-ADForest).Domains }
Else { $Forests = $Domains }
[array]$Attributes = @("UserPrincipalName", "DisplayName", "DistinguishedName", "objectClass", "mail")

$global:FormatEnumerationLimit = -1

# Add Additional Arrays together
If ($IncludeExchange)
{
    $schema = [directoryservices.activedirectory.activedirectoryschema]::getcurrentschema()
    $ExchTest = $schema.FindClass("user").OptionalProperties | ? { $_.Name -match "msExchRecipientTypeDetails" }
    If ($ExchTest)
    {
        $ExchangeAttributes = @("proxyAddresses", "msExchRecipientDisplayType", "msExchRecipientTypeDetails", "mailnickname", "targetAddress")
        $Attributes += $ExchangeAttributes
    }
    Else
    {
        Write-Host -ForegroundColor Yellow "The Active Directory schema has not been extended for Microsoft Exchange. From the"
        Write-Host -ForegroundColor Yellow "Exchange media, please run 'setup.exe /IAcceptExchangeServerLicenseTerms /PS'"
        Write-Host -ForegroundColor Yellow "to extend the schema. Since the schema has not already been extended for this"
        Write-Host -ForegroundColor Yellow "product, no data is stored in Active Directory in any of these attributes."
        Write-Host -ForegroundColor Yellow "For more information, please see:"
        Write-Host -ForegroundColor Yellow "https://docs.microsoft.com/en-us/exchange/plan-and-deploy/prepare-ad-and-domains"
    }
}
If ($IncludeSIP)
{
    $schema = [directoryservices.activedirectory.activedirectoryschema]::getcurrentschema()
    $SIPTest = $schema.FindClass("user").OptionalProperties | ? { $_.Name -match "msRTCSIP-PrimaryUserAddress" }
    If ($SipTest)
    {
        $SIPAttributes = @("msRTCSIP-PrimaryUserAddress")
        $Attributes += $SIPAttributes
    }
    Else
    {
        Write-Host -ForegroundColor Yellow "The Active Directory schema has not been extended for Microsoft Live Communications"
        Write-Host -ForegroundColor Yellow "Server, Office Communications Sever, Lync Server, or Skype for Business Server."
        Write-Host -ForegroundColor Yellow "From the Skype for Business Server media, run 'Install-CsAdServerSchema' to extend"
        Write-Host -ForegroundColor Yellow "the schema. Since the schema has not already been extented for any of these"
        Write-Host -ForegroundColor Yellow "products, no data is stored in Active Directory in any of these attributes."
        Write-Host -ForegroundColor Yellow "For more information, please see:"
        Write-Host -ForegroundColor Yellow "https://docs.microsoft.com/en-us/powershell/module/skype/install-csadserverschema"
    }
}

If ($LDAPStyle)
{
    # Build LDAP Filter
    [string]$LDAPFilter = "(&(|(&(objectClass=user)(!objectClass=computer))(objectClass=group)(objectClass=contact))(|(userprincipalname=$address)(mail=*$address)))"
    
    If ($IncludeExchange)
    {
        $LDAPFilter = $LDAPFilter.Substring(0, $LDAPFilter.Length - 2) + "(proxyaddresses=*$address)(targetaddress=smtp:$address)))"
    }
    
    If ($IncludeSIP)
    {
        $LDAPFilter = $LDAPFilter.Substring(0, $LDAPFilter.Length - 2) + "(msRTCSIP-PrimaryUserAddress=*$address)))"
    }
    
    If ($Credential)
    {
        Foreach ($Domain in $Forests)
        {
            Write-Host -ForegroundColor Yellow "Searching $Domain for $address"
            Get-AdObject -Credential $Credential -Server $Domain -LDAPFilter $LDAPFilter -Properties $Attributes | Select $Attributes | Out-String | % { FormatColor -StringMatch $($address) -HighlightColor `$($Color) }
        }
    }
    Else
    {
        Foreach ($Domain in $Forests)
        {
            Write-Host -ForegroundColor Yellow "Searching $Domain for $address"
            Get-AdObject -Server $Domain -LDAPFilter $LDAPFilter -Properties $Attributes | Select $Attributes | Out-String | % { FormatColor -StringMatch $($address) -HighlightColor `$($Color) }
        }
    }
}
Else
{
    $Filter = "objectClass -ne `"computer`" -and UserPrincipalName -eq `"$address`" -or mail -eq `"$address`""
    If ($Address -match "@")
    {
        If ($IncludeExchange -and $IncludeSIP)
        {
            $Filter = "objectClass -ne `"computer`" -and Userprincipalname -eq `"$address`" -or mail -eq `"$address`" -or msRTCSIP-PrimaryUserAddress -like `"`*`:$address`" -or proxyAddresses -like `"`*`:$address`""
        }
        If ($IncludeExchange)
        {
            $Filter = "objectClass -ne `"computer`" -and UserPrincipalName -eq `"$address`" -or mail -eq `"$address`" -or proxyAddresses -like `"`*`:$address`""
        }
        If ($IncludeSIP)
        {
            $Filter = "objectClass -ne `"computer`" -and Userprincipalname -eq `"$address`" -or mail -eq `"$address`" -or msRTCSIP-PrimaryUserAddress -like `"`*`:$address`""
        }
        
    }
    if ($Address -like "*x500:*")
    {
        $Filter = "objectClass -ne `"computer`" -and proxyaddresses -like `"`*$($address)`*`""
    }
    
    Foreach ($Domain in $Forests)
    {
        if ($LargeEnvironment)
        {
            Write-Host -ForegroundColor Cyan "Look who has a big environment!"
            [array]$global:OUs = Get-ADObject -Filter { objectClass -eq "container" -or objectClass -eq "organizationalUnit" } -Server $Domain
            $i = 1
            
            # Iterate through OUs
            foreach ($OU in $OUs)
            {
                Write-Progress -Activity "Searching $($OU) for $($Address)" -PercentComplete (($i / $OUs.Count) * 100) -Status "$($OUs.Count - $i) OUs remaining" -Id 1
                $params = @{ }
                $SearchBase = $OU.DistinguishedName
                $SearchScope = "OneLevel"
                If ($Credential) { $params.Add('Credential', $Credential) }
                If ($SearchBase) { $params.Add('SearchBase', $SearchBase) }
                If ($Attributes) { $params.Add('Properties', $Attributes) }
                If ($SearchScope) { $params.Add('SearchScope', $SearchScope) }
                If ($Filter) { $params.Add('Filter', $Filter) }
                $Results = Get-ADObject @params
                If ($Results.Count -ge 1) { $Results | Out-String | % { FormatColor -StringMatch $address -HighlightColor `$($Color) } }
                $i++
            }
        }
        Else
        {
            Write-Host -ForegroundColor Yellow "Searching $Domain for $address"
            $Results = Get-ADObject -Server $Domain -Filter $Filter -Properties $Attributes
            $Results | Out-String | % { FormatColor -StringMatch $address -HighlightColor `$($Color) }
        }
    }
}