Get-ADUser times out after 2 minutes

This past week I was approached by a coworker that had a script which was timing out in less than 30 minutes - the default ADWS timeout. They were using get-aduser with a few conditions in the filter parameter, resulting in only about 30 user accounts being returned. The query was randomly timing out and there was no immediate clue as to why in the error message. This is being run against a complex ad environment with 80k+ users in the environment. After doing some searching around the error results from the timeout between paginated results. After finding this page the answer became obvious.

Because there are so few results being returned due to the filter in such a large environment - and the default pagination size is 256 results the timeout of two minutes is being hit. In this case - since there were only 30 or less results the pagination limit of 256 was never hit and therefore if the query took more than two minutes an error was returned. The simple solution is to reduce the number of results returned on each “page” of results by setting the parameter ResultPageSize to a lower number. In this case, because they were only expecting 30 / 80k+ users to be returned we set the ResultPageSize parameter to 1. This means that for each result returned, the two minute time limit is once again refreshed preventing the query from timing out.