Skip to content

Instantly share code, notes, and snippets.

@PshMike
Last active March 18, 2020 06:05
Show Gist options
  • Save PshMike/017af8b1db5ffec77e46f1d3a41c3662 to your computer and use it in GitHub Desktop.
Save PshMike/017af8b1db5ffec77e46f1d3a41c3662 to your computer and use it in GitHub Desktop.
Get Active Directory user info using ADSI with no dependency on native AD Cmdlets
Function Get-myADUserInfo
{
[CmdletBinding()]
param
(
[string[]]$Username
)
Begin
{
try
{
$NamingContext = (([ADSI]"LDAP://RootDSE").DefaultNamingContext)[0]
Write-Verbose "Active Directory Forest Configuration container DN is $NamingContext"
}
catch
{
$NamingContext = $null
Write-Error 'unable to connect to Active Directory'
}
}
Process
{
if ($NamingContext)
{
foreach ($v in $Username)
{
try
{
$SearchBase = [ADSI]"LDAP://$NamingContext"
$Filter = "(sAMAccountName=$v)"
$Properties = @("cn", "name", "displayName", 'mail')
$Searcher = [System.DirectoryServices.DirectorySearcher]::new($SearchBase, $Filter, $Properties, [System.DirectoryServices.SearchScope]::Subtree)
$SearchResults = $Searcher.FindAll()
$info = @{
samAccountName = $v;
cn = ($SearchResults.Properties['cn'])[0];
displayName = ($SearchResults.Properties['displayName'])[0];
mail = ($SearchResults.Properties['mail'])[0];
}
}
catch
{
$info = [pscustomobject][ordered]@{
samAccountName = $v;
cn = $null
displayName = $null
mail = $null
}
}
$info
}
}
}
End
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment