In my last blog, I provided a sample PowerShell script that shows how to use the System.DirectoryServices namespace from .NET Framework to bulk create users. Now I will show you can you can use the same namespace to search the Active Directory.
We have a lot of customers wanting to get the last time a user has logged on the system. Since there is no way to create an LDAP query to give you the last time a user has logged on, I figured that it is best to get all the users into memory and then filter them using PowerShell’s handy cmdlets to do the work.
First, I have to create the function that enumerates all the users. I did this by using the System.DirectoryServices.DirectoryEntry class and System.DirectoryServices.DirectorySearcher class. The section of code below shows how to do this:
You will need to set some of the variables ahead of time that I normally put at the beginning of the script:
I then save all the users found and store it in a variable called $allusers, which is the unfiltered list of users.
I need to filter down the list and only include users that do have logged into the system. If a user has not logged into the system, the lastLogonTimestamp does not exist, so I filtered it using the command below and stored it in a variable called $withlastlogons:
I then created a new variable called $filterusers where it is a modified version of $withlastlogons. I did this because the lastLogonTimestamp property value needed to be converted so I can compare it with date values that are native to PowerShell.
The last thing I had to do is to filter it relative to the current date. If I want to pull all the users that has logged and it has been over 10 days since they last logged on, I would use the filter:
Below is the final code along with some other samples on how to pull the data: