#powershell Script: Find Active Directory User II (Update v1.10)

The Find-AdUserII function listed here is an update to this. It now accepts a text parameter which is used to search for an AD user based on a number of common properties like displayname or samaccountname. Using this as a starting point, …
… you can customize the search criteria to any supported AD user attributes.

Enjoy!

################################################################################
# Copyright (c) 201x-2017 leedesmond.com
# All Rights Reserved. Use at your own risk and responsibility.
# Find-AdUserII.ps1
# Version 1.10
#
# USAGE:
# Find-AdUserII “desmond lee” #displayname
# Find-AdUserII “dlee” #samaccountname
#
# OUTPUT:
# An array of matching users’ AD properties.
#
################################################################################
function Find-AdUserII
{
param([string]$id)

$id = $id.Trim();

$curforest = [DirectoryServices.ActiveDirectory.forest]::GetCurrentForest();
$rootdomain = $curforest.RootDomain.Name;
$base = $curforest.Schema.Name;
$base = $base.SubString($base.IndexOf(“,DC”)+1);
$users = @();

$curforest.Domains | % {
if ($_.Name -ne $rootdomain) {
$pfx = $_.Name.SubString(0,$_.Name.IndexOf(“.”));
$dom = “LDAP://DC=$pfx;$base”;

$root = New-Object System.DirectoryServices.DirectoryEntry $dom;
$searcher = New-Object System.DirectoryServices.DirectorySearcher;
$searcher.SearchRoot = $root;
$searcher.filter = “(&(objectClass=user)(displayname=$id))”;
$users += $searcher.FindAll(); #FindOne()

if ($users.count -eq 0)
{
$searcher.filter = “(&(objectClass=user)(samaccountname=$id))”;
$users += $searcher.FindAll(); #FindOne()
}
if ($users.count -eq 0)
{
$id1 = “sip:$id”
$searcher.filter = “(&(objectClass=user)(msrtcsip-primarysipaddress=$id1))”;
$users += $searcher.FindAll(); #FindOne()
}
if ($users.count -eq 0)
{
$searcher.filter = “(&(objectClass=user)(mail=$id))”;
$users += $searcher.FindAll(); #FindOne()
}
}
}
Write-Output $users;
} #Find-AdUserII()

Leave a Reply