cancel
Showing results for 
Search instead for 
Did you mean: 

[PowerShell] Get the last user activities from Directory Insights

shawnsong
Rising Star II
Rising Star II

I heard from a lot of our customers are asking for this - like the good old days we were tracking the "last logon event" 😉 

Here is my take - leverage on the event goldmine Directory Insights (the user & admin events) via the JC pwsh module of course.  

The Use Case

  • Get the last user activities for all and generate a report in CSV format - for the past X number of days. 
  • Get an insight of the users who don't have activity (for the past 30 days i.e.) - especially in the context of the remote working culture as the new norm. 

 

Here is code

p.s. You need PowerShell version 7 to run this script. 

[Update: 28th Dec 2023] - Added the local username login activities when it has been taken over by the JC user. 

[Update: 10th Jan 2024] - Boosted the performance of the overall runtime. Requires the latest JC powershell module v2.9.1. 

Note: Please make sure you are using the latest JC Powershell module.

 


# Building the Report Object Container
$outputReport = @()

# Set the number of days you wanted to back track
$tracebackDays = 30

# Get all users with usernames only
$usernames = Get-JCUser -returnProperties username,systemUsername
foreach ($u in $usernames){ 
    $report = "" | select username,geoip,service,success,client_ip,timestamp,details,event_type,useragent,localUserName
    
    $reportUser = $u.username
    if ("" -ne $u.systemUsername){
      $reportUser = ($u.systemUsername).ToLower()

    }
    # Callin JC DI and back tracking the days defined above
    $loginEvent = Get-JcSdkEvent -Service:('all') -StartTime:((Get-date).AddDays(-$tracebackDays))`
      -SearchTermAnd @{"initiated_by.username" = $reportUser} -ErrorAction SilentlyContinue |`
      sort-object -Descending $_.timestamp -Bottom 1

    $report.username = $u.username
    $report.timestamp = "n.a."
    $report.details = "user has no activity for the past $tracebackDays days "
    $report.localUserName = $u.systemUsername

    
    if ($null -ne $loginEvent){
        $report.geoip = $loginEvent.geoip
        $report.service = $loginEvent.service
        $report.success = $loginEvent.success
        $report.client_ip = $loginEvent.client_ip
        $report.timestamp = $loginEvent.timestamp
        $report.details = $loginEvent.message
        $report.event_type = $loginEvent.event_type
        $report.useragent = $loginEvent.useragent
    }
    $outputReport += $report
}
$outputReport | export-csv lastUserActReport.csv

 

 

 

 

 

1 REPLY 1

VigneswaraRao
Novitiate I

Thanks Shawn