@@ -30,43 +30,56 @@ This is a support that is used to check if given UPN already exists in the AD en
3030``` powershell
3131function Test-UPNExist
3232{
33+ <#
34+ .SYNOPSIS
35+ Cmdlet will check if a given UPN exists in the forest.
36+
37+ .DESCRIPTION
38+ Cmdlet is a diagnostic tool to check if a given UPN is already assigned to a user in the forest.
39+
40+ .PARAMETER UPN
41+ A string representing the UPN to check for uniqueness.
42+
43+ .PARAMETER AdServer
44+ A string representing the name of the domain controller to be used for the check, if parameter
45+ is not specified the closest Global Catalog is used.
46+
47+ .EXAMPLE
48+ PS C:\> Test-UPNExist -UPN 'John.Doe@example.com'
49+ #>
50+
3351 [CmdletBinding()]
34- param (
52+ param
53+ (
3554 [Parameter(Mandatory = $true)]
55+ [ValidateNotNullOrEmpty()]
3656 [string]$UPN,
37-
38- [string]$Server
57+ [ValidateNotNullOrEmpty()]
58+ [string]$AdServer
3959 )
40-
41- try
60+
61+ if ([string]::IsNullOrEmpty($AdServer) -eq $true)
4262 {
43- if ($Server)
44- {
45- $ldapPath = "LDAP://$Server"
46- }
47- else
48- {
49- $forest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
50- $gc = $forest.FindGlobalCatalog()
51- $ldapPath = "GC://$($gc.Name)"
52- }
53- $domain = New-Object System.DirectoryServices.DirectoryEntry($ldapPath)
54- $searcher = New-Object System.DirectoryServices.DirectorySearcher($domain)
55- $searcher.SearchScope = "Subtree"
56- $searcher.PageSize = 1000
57- $searcher.Filter = "(&(objectCategory=person)(userPrincipalName=$UPN))"
58- [void]($searcher.PropertiesToLoad.Add("userPrincipalName"))
59-
60- $result = $searcher.FindOne()
61- return $null -ne $result
63+ $adForest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
64+ [string]$ldapPath = '{0}{1}' -f 'GC://', $($adForest.FindGlobalCatalog().Name)
6265 }
63- catch
66+ else
6467 {
65- Write-Error "Error checking UPN existence: $_"
66- throw
68+ [string]$ldapPath = '{0}{1}' -f 'LDAP://', $AdServer
6769 }
70+
71+ # Instantiate required objects and run query
72+ $adDomain = New-Object System.DirectoryServices.DirectoryEntry($ldapPath)
73+ $adSearcher = New-Object System.DirectoryServices.DirectorySearcher($adDomain)
74+ $adSearcher.SearchScope = 'Subtree'
75+ $adSearcher.PageSize = 1000
76+ $adSearcher.Filter = "(&(objectCategory=person)(userPrincipalName=$UPN))"
77+ [void]($adSearcher.PropertiesToLoad.Add("userPrincipalName"))
78+
79+ [array]$searchResult = $adSearcher.FindOne()
80+
81+ return $null -ne $searchResult
6882}
69-
7083```
7184
7285Here's a summary explanation of the parameters:
0 commit comments