check interactive sign in | powershell

Viewed 120

I am writing a PowerShell Script that get users with Last interactive sign in but actually I am not sure about it and some codes are missing because I don't have background on it can someone help..

...

##if there is no sign in from user - - And- user not performed an interactive sign in

...

if ($Null -eq $User.SignInActivity ) {

        #if company contains SP
    if($User.companyName -eq 'company1') {

        #if user not performed an interactive sign in 
        if ($Null -eq $User.SignInActivity.interactive ) {

            $err= "No interactive sign in detected"

        write-host "$upn $date $company $country $city $err  "
        
    
}

...

I wanted the code to print the following : ErrorNumber,UPN,date,Service Provider,Country,City,Error,Last interactive sign in (UTC),Last interactive sign in (user local time),Last App

but I don't know how to get the last 3 attribute please help!! + user should has not performed an interactive sign in between 12.00 AM and 11.59 PM on the previous weekday Weekdays only: all worldwide staff have weekend on Friday and Saturday

1 Answers

By using the below script you can get last login time and I followed SO-Thread:

$Users= ((Get-AzureADUser -Filter "AccountEnabled eq true" )| Where-Object { $_.LastSignInDateTime -le (Get-Date).AddDays(-30) } )
$AllSiginLogs = Get-AzureADAuditSignInLogs -All $true
foreach($user in $Users)
{          
$LoginRecord = $AllSiginLogs | Where-Object{ $_.UserId -eq $user.ObjectId  } | Sort-Object CreatedDateTime -Descending
    if($LoginRecord.Count -gt 0){
        $lastLogin = $LoginRecord[0].CreatedDateTime
    }else{
        $lastLogin = 'no login record'
    }            
Write-Host "Last logon time  : " $lastLogin
Write-Host " "
Write-Host " " 
            }

enter image description here

Refer here for complete understanding of how to do it with PowerShell.

Alternatively, I have tried Graph Explorer and I get required output as below and I followed Microsoft-Document for below http requests:

 https://graph.microsoft.com/beta/users?filter=signInActivity/lastSignInDateTime le 2022-09-15T11:59:00Z

enter image description here

List of all users:

https://graph.microsoft.com/beta/users?$select=displayName,signInActivity

enter image description here

Related