Reputation: 39
Interesting quiz question I've come across. Usually when I'm searching for an ADUser I'm looking for users matching a certain name.
The quiz question I'm stuck on is:
List the ADUsers with last names starting from S to Z in reverse alphabetical order in a single line.
I'm thinking of using Get-ADUser -Filter
Or perhaps Get-ADUser Where-Object and then specifying the range and selecting that I want the results to be sorted in reverse alphabetical order.
The issue I'm having is difficulty finding documentation on how to correctly use -Filter or Where-Object.
I realize these are contextual so it depends which query I want to apply them to, but this is the context.
Appreciate your insights as always.
Upvotes: 0
Views: 6594
Reputation: 40958
There's two steps:
Sorting is easy (Sort-Object Surname -Descending
), so we'll start with the filter. Don't use Where-Object
because that filtering is done locally. So you would end up asking the server for every user object, which will take a long time. Then you're throwing out most of the results. Instead, ask the server for only what you need.
Personally, I prefer to use -LDAPFilter
since I'm comfortable with that. It's not as readable, but anything you put in -Filter
has to be translated to an LDAP filter anyway, so it sometimes gives you more control to use it directly. In this case, it doesn't really matter, so I'll show you both.
You can use <=
and >=
with strings and it will do a lexicographical comparison. Since I'm using -LDAPFilter
here, I need to use the actual attribute name, which is sn
:
Get-ADUser -LDAPFilter "(&(sn>=s)(sn<=z))" | Sort-Object Surname -Descending
In other LDAP libraries, you'd include (objectClass=user)
, but Get-ADUser
adds it automatically. More info on LDAP query syntax here: Active Directory: LDAP Syntax Filters
But if you really want to just use -Filter
, you need to use the PowerShell comparison operators. But you can also use the PowerShell property name of "Surname":
Get-ADUser -Filter "Surname -ge 's' -and Surname -le 'z'" | Sort-Object Surname -Descending
The Get-ADUser
cmdlet will translate that into basically the same LDAP filter we used in -LDAPFilter
above.
You technically can make the AD server do the sorting, but with any database in general, it's a bad idea: LDAP: how to do server-side sorting and why it’s a bad idea
I think the biggest downside to server-side sorting is this:
the server cannot return any objects until a completed result set is constructed.
AD will return "pages" of results as they're available. So you can starting working with the results before the server has even finished finding all the results. But if it has to sort, it can't do that.
Upvotes: 2