You can look up user with ADSISearcher directly from PowerShell without loading the ActiveDirectory module. The [ADSISearcher] type accelerator creates a .NET DirectorySearcher object that queries Active Directory through LDAP.
Look up a user with ADSISearcher
ADSISearcher is a PowerShell type accelerator for the native System.DirectoryServices.DirectorySearcher dotnet class.
Example:
([ADSISearcher]"(sAMAccountName=USERNAME)").FindOne().Properties["userPrincipalName"]
Replace USERNAME with the user's sAMAccountName. FindOne() returns the first matching directory object, and the final expression reads its userPrincipalName property.
Handle a missing account
$result = ([ADSISearcher]'(sAMAccountName=USERNAME)').FindOne()
if ($null -eq $result) {
Write-Warning 'User was not found.'
} else {
$result.Properties['userPrincipalName']
}
Do not insert untrusted text directly into an LDAP filter; filter metacharacters must be escaped. Microsoft describes the underlying query object in the DirectorySearcher reference. See also querying deleted AD users with PowerShell.

Comments