
close
close
I hope by now that you are comfortable using the Active Directory Searcher object. If you have no idea what I am talking about, take a few minutes to get caught up on the previous articles, Discovering the Active Directory Searcher with PowerShell and Finding Groups with the Active Directory Searcher and PowerShell.
Let’s expand the scope and find multiple objects with user accounts.
$searcher = New-Object system.DirectoryServices.DirectorySearcher $searcher.SearchRoot = "LDAP://ou=employees,dc=globomantics,dc=local" $searcher.filter = "(objectclass=user)" $props = "distinguishedname","name","samaccountname","title","department","directreports", "whencreated","whenchanged","givenname","sn","userprincipalname","adspath" foreach ($item in $props) { $searcher.PropertiesToLoad.Add($item) | out-null }
I have limited my search to an OU that contains my active user accounts. I have also specified the properties I want to retrieve. Once the searcher is configured, I can find all matching objects.
foreach ($user in $all[4]) { $h = @{} foreach ($p in $props) { $value = $user.Properties.item($p) if ($value.count -eq 1) { $value = $value[0] } $h.add($p,$value) } new-object psobject -property $h }
advertisment
Function Convert-ADSearchResult { [cmdletbinding()] Param( [Parameter(Position = 0,Mandatory,ValueFromPipeline)] [ValidateNotNullorEmpty()] [System.DirectoryServices.SearchResult]$SearchResult ) Begin { Write-Verbose "Starting $($MyInvocation.MyCommand)" } Process { Write-Verbose "Processing result for $($searchResult.Path)" #create an ordered hashtable with property names alphabetized $props = $SearchResult.Properties.PropertyNames | Sort-Object $objHash = [ordered]@{} foreach ($p in $props) { $value = $searchresult.Properties.item($p) if ($value.count -eq 1) { $value = $value[0] } $objHash.add($p,$value) } new-object psobject -property $objHash } End { Write-Verbose "Ending $($MyInvocation.MyCommand)" } }
The function is designed to take pipelined input from any search result.
$all | Convert-ADSearchResult | Select Name,UserPrincipalName,Department,Title,When* | Out-GridView
$searcher.filter = "(&(objectclass=user)(department=finance))"
You need to enclose each filter part inside the (&) construct, which tells PowerShell to search for both of these things.
More in PowerShell
Microsoft’s New PowerShell Crescendo Tool Facilitates Native Command-Line Wraps
Mar 21, 2022 | Rabia Noureen
Most popular on petri