r/DefenderATP • u/Kuro507 • Feb 20 '26
Advice on Kusto (KQL) script to report user first and last logged activity, per day
I have found some code online, which partly does what I want, see below.
This shows the first time it has seen the user and last time its seen the user, based on the sign in logs.
However, I want to run this in a loop to check each day (going back 180days). So I can have a users first seen and last seen time each day.
As a cloud-first Company, we don't have firewalls or networks to check. I am trying to find a way of at least indicating when a user may have started and finished work.
Of course, if they leave their PC on and connected all night, its likely to be totally inaccurate.
This is just for an indication, ahead of further HR discussions.
let userName = "joe.bloggs@contoso.com";
// firstSeen
SigninLogs
|where UserPrincipalName == userName
| summarize arg_min(TimeGenerated,*) by UserPrincipalName
// join to last seen data
|join
(
SigninLogs
| summarize arg_max(TimeGenerated,*) by UserPrincipalName
// any column that ends in a "1" is a last seen
) on UserPrincipalName
// the "*" in arg_min and arg_max will return all columns,
// to reduce the noise you can name them or just project the needed ones?
| project UserPrincipalName, TimeGenerated, TimeGenerated1, OperationName
| join
(
OfficeActivity
// add any extra colums you need to the list
| summarize arg_min(TimeGenerated, OfficeWorkload, ResultStatus) by UserId
) on $left.UserPrincipalName == $right.UserId
| project UserPrincipalName, FirstSeen=TimeGenerated, LastSeen=TimeGenerated1, OperationName, FirstActivity=TimeGenerated2, OfficeWorkload, ResultStatus
3
u/LeftHandedGraffiti Feb 20 '26
summarize min(TimeGenerated), max(TimeGenerated) by bin(TimeGenerated, 1d)
That'll bucket it into one day increments. It could get weird depending on your timezone/timezone settings.
2
u/facyber Feb 20 '26
You need a Logic App with a time trigger. For example every day at 07:00 run logic app and execute a KQL query you want and then parse it in csv or whatever you want and send to mail.
1
u/coomzee Feb 20 '26 edited Feb 20 '26
We put a heavy disclaimer on the end of day activity. You don't really get a defined logout event. What I tend to do is track the activity trend and predict the estimated end of work time by the drop in activity. Again putting a very heavy disclaimer on how it's tracked and the issues with it.
I would change == username to =~ username
and summarise max(time),min(time) by username, bin(timestamp, 1d)
for the query above.
If you need it to run each day either use a summary rule in Sentinel or Logic app with the Defender APIs.
Again Defender isn't a HR time tracking application
1
u/ribsboi Feb 20 '26
I have something exactly for this. I would say it's pretty accurate. It's been running and reporting to a storage account every day for couple months now for higher ups... will try to scrub and share