Page 1 of 1

Active Directory user activity (last logon) report with PowerShell

Posted: 01 Feb 2023, 16:20
by daniele
ORIGINAL ARTICLE: https://4sysops.com/archives/build-an-a ... owershell/
ALL RIGHTS TO THE AUTHOR(S) AND OWNER(S) OF THE ORIGINAL ARTICLE

Passaggi da riga di comando Powershell per ottenere lista degli utenti Active Directory con data e ora di ultimo logon

First, I'll query all DCs in my environment with Get-AdDomainController. The command below will return the fully qualified domain names (FQDNs) of every DC

Code: Select all

$dcs = Get-ADDomainController | Select-Object -ExpandProperty HostName

Next, I'll need to query each DC for every user who has a LastLogonDate. To do this, I'll use Get-AdUser and filter on users having a last logon date attribute.

Code: Select all

$users = @()
foreach ($dc in $dcs) {
    $users += Get-ADUser -Filter "lastLogonDate -like '*'" -Properties LastLogonDate -Server $dc | Select-Object -Property samAccountName,LastLogonDate
}

Once I have all of the users with a last logon date, I can now build a report on this activity. I can create reports in PowerShell lots of different ways.

First, I can pipe the results of my query to the Out-GridView command. This returns an interactive GUI allowing you to sort, filter, and view results in many different ways.

REPORT VISTA A VIDEO

Code: Select all

$users | Out-GridView
Or I can pipe to a CSV file which will be best suitable for editing and analysis

REPORT SU FILE CSV

Code: Select all

PS> $users | Export-Csv -Path 'C:\UserActivity.csv' -NoTypeInformation
PS> import-csv C:\UserActivity.csv

samaccountname lastlogondate
-------------- -------------
techsnips      3/21/2019 10:24:22 PM
jdoe           3/5/2019 6:43:07 PM
jjones         3/14/2019 8:27:20 AM
Microsoft.NET  3/19/2019 1:02:03 AM