Skip to content

Instantly share code, notes, and snippets.

@kevinCefalu
Created August 26, 2021 17:01
Show Gist options
  • Save kevinCefalu/d6bde36147ed76e6a0512c9abd48f8d7 to your computer and use it in GitHub Desktop.
Save kevinCefalu/d6bde36147ed76e6a0512c9abd48f8d7 to your computer and use it in GitHub Desktop.
Get the last recorded login timestamp for users across multiple domain controllers
#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