Getting All LDAP Users via Sitecore Powershell

So say you need get all of the LDAP provided users in your system in a Powershell script. Say also that your LDAP setup is set to only return a fixed maximum number of records when a search is performed. What are you gonna do?

Sure, I could have altered the setting to give me bigger chunks of users, but I was in production and getting a setting change like that deployed could be days or weeks away. I needed something quicker.

I remembered back to a weird situation that I discovered with Sitecore queries where performing multiple descrete queries and smashing their results together was far faster than using a query with multiple “or” statements. That same tactic would work here.
So I decided to use the alphabet to my advantage and perform queries looking for small enough groups of users that would always be under the “get all” limit. In my case it was three letters (“aaa*”, “aab*”, “aac*”, etc…).

First I create a string of all the letters in the alphabet. I could’ve just typed them out but what fun is that, especially when you can grab the code snippet from Stack Overflow?

for ($test = 0; $test -lt 26; $test++)
	$allLetters = $allLetters + [char](65 + $test)

Then I looped through those strings three times to get all of our potential filters. Inside those loops I took advantage of Powershell’s “powerfull” string formatting to build my queries and then ran them. I then smashed the result of those queries in with the previous results.

foreach ($firstletter in $allLetters.TocharArray()) { 
	foreach ($secondletter in $allLetters.TocharArray()) {
		 foreach ($thirdletter in $allLetters.TocharArray()) {
			$filter = "MyLDAPDomain\$firstletter$secondletter$thirdletter*"
			$letterUsers = (Get-User -Filter $filter)
			$allUsers = $allUsers + $letterUsers

This takes a while to run, but it’s very thorough and worked well to solve my problem. If you have a similar issue, it might solve it too.

About The Author