locked
Powershell Script for exporting User's Last LogonTime RRS feed

  • Question

  • Dear All,

    I try to create a Ticket that shows me the last logon time of every user...but unfortunately it doesnt' work properly.

    Here's the code:

    Import-Module AzureADPreview
    
    AzureADPreview\Connect-AzureAD
    
    $user = Get-AzureADUser -All $true
    $report = @()
    
    $displayName = @{n='DisplayName';e={$PSItem.UserDisplayName}}
    $lastLogon = @{n='LastLogon';e={Get-Date -Date $PSItem.CreatedDateTime -Format G}}
    
    <#foreach ($u in $user)
    { #>
        $upn = $u.UserPrincipalName
        $report += Get-AzureAdAuditSigninLogs - | Select-Object -Property $displayName,UserPrincipalName,$lastLogon
    #} 
    
    $report | Export-Csv -Path ("C:\users\gbu101\last_logon.csv" -f $env:USERPROFILE) -NoTypeInformation -Delimiter ';' -Encoding UTF8


    I've disabled the foreach-loop  for testing. When I run the script this way, it tells me that every single user logged in at the current day and every user exactly logged in a minute after the other..which can't be true. When I filter it with "CreatedDateTime" it just doesn't export anything at all.

    Here's a different version of the script:

    Import-Module AzureADPreview
    
    AzureADPreview\Connect-AzureAD
    
    $user = Get-AzureADUser -All $true
    $report = @()
    
    $displayName = @{n='DisplayName';e={$PSItem.UserDisplayName}}
    $lastLogon = @{n='LastLogon';e={Get-Date -Date $PSItem.CreatedDateTime -Format G}}
    
    foreach ($u in $user)
    {
        $upn = $u.UserPrincipalName
        $report += Get-AzureAdAuditSigninLogs -Filter "userprincipalname eq '$upn'" -Top 1 | Select-Object -Property $displayName,UserPrincipalName,$lastLogon
    }
    
    $report | Export-Csv -Path ("{0}\Desktop\aad_lastlogon.csv" -f $env:USERPROFILE) -NoTypeInformation -Delimiter ';' -Encoding UTF8


    Here I receive the following error Message:

    Get-AzureAdAuditSigninLogs : Error occurred while executing GetAuditSignInLogs 
    Code: UnknownError
    Message: Too Many Requests
    InnerError:
      RequestId: e0f3c65e-c3d4-48ee-ae5d-b5ff00475c97
      DateTimeStamp: Mon, 28 Sep 2020 08:16:53 GMT
    HttpStatusCode: 429
    HttpStatusDescription: 
    HttpResponseStatus: Completed
    At C:\Ex_Powershell\Office365_Userlist.ps1:14 char:16
    + ...  $report += Get-AzureAdAuditSigninLogs -Filter "userprincipalname eq  ...

    Do you know what I'm doing wrong?

    Thank you for your help.

    Kind regards,

    Gabriel


    • Edited by theswissgabe Tuesday, September 29, 2020 9:43 AM
    Tuesday, September 29, 2020 9:42 AM