Find-DuplicateValues.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
<#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) }
        }
    }
}