Created
August 26, 2021 17:01
-
-
Save kevinCefalu/d6bde36147ed76e6a0512c9abd48f8d7 to your computer and use it in GitHub Desktop.
Get the last recorded login timestamp for users across multiple domain controllers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Requires -Module ActiveDirectory | |
using namespace Microsoft.ActiveDirectory.Management; | |
function Get-ADUserLastLogon | |
{ | |
<# | |
.SYNOPSIS | |
Get the last recorded login for one or more users across one or more domain controllers | |
.EXAMPLE | |
PS C:\> $LoginRecords = Get-ADUser -Filter '*' | Get-ADUserLastLogon; | |
PS C:\> $LoginRecords; | |
Get a list of users, and then return the last login recorded | |
across all domain controllers for those users | |
.EXAMPLE | |
PS C:\> $LoginRecords = Get-ADUser -Filter '*' | | |
>> Get-ADUserLastLogon -DomainControllers (Get-ADDomainController -Filter { Name -like 'DC1' }); | |
PS C:\> $LoginRecords; | |
Get a list of users, and then return the last login recorded | |
across a filtered list of domain controllers for those users | |
.INPUTS | |
Microsoft.ActiveDirectory.Management.ADUser | |
Microsoft.ActiveDirectory.Management.ADDomainController[] | |
.OUTPUTS | |
System.Collections.Hashtable[] | |
#> | |
[CmdletBinding()] | |
[OutputType([HashTable])] | |
param ( | |
[Parameter(Mandatory, ValueFromPipeline)] | |
[ADUser] $User, | |
[Parameter()] | |
[ADDomainController[]] $DomainControllers = (Get-ADDomainController -Filter { Name -like '*' }) | |
); | |
process | |
{ | |
$LastLogin = [DateTime]::Parse('12/31/1600'); | |
foreach ($DomainController in $DomainControllers) | |
{ | |
$UserOnDomainController = Get-ADUser $User.SamAccountName | | |
Get-ADObject -Server $DomainController.HostName -Properties 'lastLogon' | |
$LastLoginOnDomainController = [DateTime]::FromFileTime($UserOnDomainController.LastLogon); | |
if ($LastLoginOnDomainController -gt $LastLogin) | |
{ | |
$LastLogin = $LastLoginOnDomainController; | |
} | |
} | |
if ($LastLogin -le [DateTime]::Parse('12/31/1601')) | |
{ | |
$LastLogin = $null; | |
} | |
return @{ | |
User = $User; | |
LastLogin = $LastLogin; | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment