Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <##
- purpose report entra user sign-in logs to CSV
- requires (Application): AuditLog.Read.All, Directory.Read.All
- ##>
- ## Variables
- $Now = Get-Date -Format 'yyyy.MM.dd_HH.mm.ss'
- $ReportPath = "C:\Msp\Reports\Entra\User"
- $ReportFile = "$ReportPath\UserSignInLogs_$Now.csv"
- ## MgGraph Configuration
- $Config = Import-Clixml -Path "C:\Msp\Configs\MgGraphRead.xml"
- $tenantId = $Config.TenantId
- $clientId = $Config.ClientId
- $certPrint = $Config.Thumbprint
- $cert = Get-Item "Cert:\CurrentUser\My\$certPrint"
- ## Connect to MgGraph
- Connect-MgGraph -TenantId $tenantId -ClientId $clientId -Certificate $cert -NoWelcome -ErrorAction Stop
- ## Create ReportPath if missing
- if (-not (Test-Path $ReportPath)) { New-Item -Path $ReportPath -ItemType Directory -Force | Out-Null }
- ## Graph requires UTC for the filter string
- $LookbackDate = (Get-Date).AddDays(-7).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")
- $Results = Get-MgBetaAuditLogSignIn -All -Filter "createdDateTime ge $LookbackDate and signInEventTypes/any(t: t eq 'interactiveUser')" | ForEach-Object {
- ## Adding a single quote prefix forces Excel to display the exact string format
- $LocalTime = "'" + $_.CreatedDateTime.ToLocalTime().ToString("yyyy/MM/dd HH:mm:ss")
- $UtcTime = "'" + $_.CreatedDateTime.ToString("yyyy/MM/dd HH:mm:ss")
- ## Create an object to hold just the attributes or properies we went in our log
- [PSCustomObject][Ordered]@{
- UserDisplayName = $_.UserDisplayName
- UserPrincipalName = $_.UserPrincipalName
- CreatedDateTime = $UtcTime
- CreatedDateTimeLocal = $LocalTime
- ClientAppUsed = $_.ClientAppUsed
- ConditionalAccessStatus = $_.ConditionalAccessStatus
- IPAddress = $_.IpAddress
- Status = if ($_.Status.ErrorCode -eq 0) { "Success" } else { "Failure ($($_.Status.ErrorCode))" } # PROFICIENCY: Cleaner Status reading
- IsInteractive = $_.IsInteractive
- Location = "$($_.Location.City), $($_.Location.State), $($_.Location.CountryOrRegion)".Trim(', ')
- }
- }
- ## Pipe result data to CSV file
- $Results | Export-Csv -Path $ReportFile -NoTypeInformation -Encoding utf8
- ## Script complete, disconnect from Entra
- Disconnect-MgGraph
Advertisement