PowerShell Script to Get User Last Login Date
Get-ADUser -Identity username -Properties LastLogonDate | Select-Object Name, LastLogonDate to get a user's last login date from Active Directory.Examples
How to Think About It
Get-ADUser cmdlet with the username and select the relevant property to display.Algorithm
Code
Import-Module ActiveDirectory $username = "jsmith" $user = Get-ADUser -Identity $username -Properties LastLogonDate if ($user) { Write-Output "User: $($user.Name)" Write-Output "Last Login: $($user.LastLogonDate)" } else { Write-Output "User not found." }
Dry Run
Let's trace the script for username 'jsmith' through the code
Set username
$username = "jsmith"
Get user object
$user = Get-ADUser -Identity jsmith -Properties LastLogonDate $user.Name = "jsmith" $user.LastLogonDate = "4/25/2024 10:15:30 AM"
Check if user exists
$user is not null, proceed to output
Output results
Print "User: jsmith" and "Last Login: 4/25/2024 10:15:30 AM"
| Step | Action | Value |
|---|---|---|
| 1 | Set username | jsmith |
| 2 | Get user object | Name=jsmith, LastLogonDate=4/25/2024 10:15:30 AM |
| 3 | Check user exists | True |
| 4 | Output | User: jsmith, Last Login: 4/25/2024 10:15:30 AM |
Why This Works
Step 1: Import Active Directory Module
The script starts by loading the Active Directory module with Import-Module ActiveDirectory to access AD cmdlets.
Step 2: Retrieve User Object
It uses Get-ADUser with the username and requests the LastLogonDate property to get the last login time.
Step 3: Check User Existence
The script checks if the user object was found to avoid errors when the username does not exist.
Step 4: Display Results
Finally, it prints the user's name and last login date to the console for easy reading.
Alternative Approaches
Import-Module ActiveDirectory $username = "jsmith" $user = Get-ADUser -Identity $username -Properties LastLogonTimestamp if ($user) { $lastLogon = [DateTime]::FromFileTime($user.LastLogonTimestamp) Write-Output "User: $($user.Name)" Write-Output "Approximate Last Login: $lastLogon" } else { Write-Output "User not found." }
# This requires looping through all DCs and comparing lastLogon values, which is more complex and slower but accurate.Complexity: O(1) time, O(1) space
Time Complexity
The script queries a single user from Active Directory, which is a direct lookup and runs in constant time.
Space Complexity
The script stores only one user object and a few variables, so space usage is constant.
Which Approach is Fastest?
Using LastLogonDate with Get-ADUser is fastest for single users. Querying all domain controllers is slower but more accurate.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Get-ADUser with LastLogonDate | O(1) | O(1) | Quick single user lookup |
| Get-ADUser with LastLogonTimestamp | O(1) | O(1) | Approximate login for many users |
| Query all domain controllers | O(n) | O(n) | Accurate audit across DCs |