# search based on SamAccountNamer
$strFilter = "(SAMAccountName=$username)"
$objDomain = New-Object System.DirectoryServices.DirectoryEntry
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = "Subtree"
# Add additional properties to return here
$colProplist = "name","SAMAccountName"
foreach ($i in $colPropList){
$foo = $objSearcher.PropertiesToLoad.Add($i)
}
$colResults = $objSearcher.FindAll()
# formation output results
[System.Collections.Generic.List[PSObject]] $results = @()
foreach ($objResult in $colResults){
$properties = @{}
$objResult.Properties.GetEnumerator() | ForEach-Object{
$properties.Add($_.Key,$_.Value[0])
}
$results.Add([pscustomobject]$properties)
}
$results
This snippet will allow you to search for an Active Directory user without needing to install the Active Directory PowerShell module
PS C:\> $username = "*svc*" >> $strFilter = "(SAMAccountName=$username)" >> $objDomain = New-Object System.DirectoryServices.DirectoryEntry >> $objSearcher = New-Object System.DirectoryServices.DirectorySearcher >> $objSearcher.SearchRoot = $objDomain >> $objSearcher.PageSize = 1000 >> $objSearcher.Filter = $strFilter >> $objSearcher.SearchScope = "Subtree" >> $colProplist = "name","SAMAccountName" >> foreach ($i in $colPropList){ >> $foo = $objSearcher.PropertiesToLoad.Add($i) >> } >> $colResults = $objSearcher.FindAll() >> [System.Collections.Generic.List[PSObject]] $results = @() >> foreach ($objResult in $colResults){ >> $properties = @{} >> $objResult.Properties.GetEnumerator() | ForEach-Object{ >> $properties.Add($_.Key,$_.Value[0]) >> } >> $results.Add([pscustomobject]$properties) >> } >> $results