snickasaurus

AutoReportCSV-EntraUserSigninLogs.ps1

Jan 25th, 2026 (edited)
3,761
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <##
  2.     purpose     report entra user sign-in logs to CSV
  3.     requires    (Application): AuditLog.Read.All, Directory.Read.All
  4. ##>
  5.  
  6. ## Variables
  7. $Now            = Get-Date -Format 'yyyy.MM.dd_HH.mm.ss'
  8. $ReportPath     = "C:\Msp\Reports\Entra\User"
  9. $ReportFile     = "$ReportPath\UserSignInLogs_$Now.csv"
  10.  
  11. ## MgGraph Configuration
  12. $Config         = Import-Clixml -Path "C:\Msp\Configs\MgGraphRead.xml"
  13. $tenantId       = $Config.TenantId
  14. $clientId       = $Config.ClientId
  15. $certPrint      = $Config.Thumbprint
  16. $cert           = Get-Item "Cert:\CurrentUser\My\$certPrint"
  17.  
  18. ## Connect to MgGraph
  19. Connect-MgGraph -TenantId $tenantId -ClientId $clientId -Certificate $cert -NoWelcome -ErrorAction Stop
  20.  
  21. ## Create ReportPath if missing
  22. if (-not (Test-Path $ReportPath)) { New-Item -Path $ReportPath -ItemType Directory -Force | Out-Null }
  23.  
  24. ## Graph requires UTC for the filter string
  25. $LookbackDate = (Get-Date).AddDays(-7).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
  26. $Results = Get-MgBetaAuditLogSignIn -All -Filter "createdDateTime ge $LookbackDate and signInEventTypes/any(t: t eq 'interactiveUser')" | ForEach-Object {
  27.     ## Adding a single quote prefix forces Excel to display the exact string format
  28.     $LocalTime  = "'" + $_.CreatedDateTime.ToLocalTime().ToString("yyyy/MM/dd HH:mm:ss")
  29.     $UtcTime    = "'" + $_.CreatedDateTime.ToString("yyyy/MM/dd HH:mm:ss")
  30.     ## Create an object to hold just the attributes or properies we went in our log
  31.     [PSCustomObject][Ordered]@{
  32.         UserDisplayName             = $_.UserDisplayName
  33.         UserPrincipalName           = $_.UserPrincipalName
  34.         CreatedDateTime             = $UtcTime
  35.         CreatedDateTimeLocal        = $LocalTime
  36.         ClientAppUsed               = $_.ClientAppUsed
  37.         ConditionalAccessStatus     = $_.ConditionalAccessStatus
  38.         IPAddress                   = $_.IpAddress
  39.         Status                      = if ($_.Status.ErrorCode -eq 0) { "Success" } else { "Failure ($($_.Status.ErrorCode))" } # PROFICIENCY: Cleaner Status reading
  40.         IsInteractive               = $_.IsInteractive
  41.         Location                    = "$($_.Location.City), $($_.Location.State), $($_.Location.CountryOrRegion)".Trim(', ')
  42.     }
  43. }
  44.  
  45. ## Pipe result data to CSV file
  46. $Results | Export-Csv -Path $ReportFile -NoTypeInformation -Encoding utf8
  47.  
  48. ## Script complete, disconnect from Entra
  49. Disconnect-MgGraph
Advertisement