Wednesday, August 17, 2022

Get-ADUser Filter Count Incorrect

 Let's say you have a number of AD records, and you wanted to search for how many of them contain a certain value. You might do something like this:

(Get-ADUser -Filter 'Department -eq "Accounting"').Count

If you have 20 people in the Accounts Department, then this will correctly return 20.

However, let's say there is only one person in that department. That line will return $Null instead of 1

The reason is that the return of one record is not an array and the method 'count' requires an array. The solution is to cast the result to an array. The following will correctly return a '1' for that lonely accountant:

([array](Get-ADUser -Filter 'Department -eq "Accounting"')).Count

Cheers!

No comments:

Post a Comment