UserLastLogon -Export

Viewed 867

Hi I'm trying to export a list of AD users based on "Last Logon"
I've scripted using base powershell however I'd be interested if anyone can find a solution using "AzureAD to Powershell" commands.

I've gotten as far as getting the list however I cannot export it to any file type because of how it generates through the loop. End result I'm looking for is to be able to organize the data to see which users have been inactive?

Import-Module ActiveDirectory

function Get-ADUserLastLogon([string]$userName) {

    $dcs = Get-ADDomainController -Filter {Name -like "*"}
    $time = 0
    foreach($dc in $dcs) { 
        $hostname = $dc.HostName
        $user = Get-ADUser $userName | Get-ADObject -Properties lastLogon 
        if($user.LastLogon -gt $time) {
            $time = $user.LastLogon
        }
        
    }
    
    $dt = [DateTime]::FromFileTime($time)
    Write-Host $username "last logged on at:" $dt
}

$unames = Get-ADUser -Filter 'ObjectClass -eq "User"' | Select -Expand SamAccountName 
foreach ($uname in $unames) { Get-ADUserLastLogon($uname); } 
1 Answers

In Azure AD, we can get all user Sign-ins records on Azure Portal or using Azure AD PowerShell. If you are looking for a way by PowerShell to export Azure AD users last login list with user account status (enabled or not), just try the code below:

Connect-AzureAD

$AllUsers =  Get-AzureADUser -All $true
$AllSiginLogs = Get-AzureADAuditSignInLogs -All $true

$results = @()
foreach($user in $AllUsers){

    $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'
    }
    $item = @{
        userUPN=$user.UserPrincipalName
        userDisplayName = $user.DisplayName
        lastLogin = $lastLogin
        accountEnabled = $user.AccountEnabled
    }
    $results += New-Object PSObject -Property $item  
    
}
$results | export-csv -Path d:\result.csv -NoTypeInformation

export to .csv file Result: enter image description here

There is one thing that you should know, for different Azure AD service tier, the time that Azure AD keep these data is different, details see here.

Related