Skip to content

Get tenant signins

directorcia edited this page Apr 17, 2025 · 4 revisions

Microsoft 365 Sign-In Report Script (Graph API)

Designed to retrieve and report on user sign-in activities from a Microsoft 365 tenant using the Microsoft Graph API.


1. Script Parameters

The script accepts five optional parameters:

  • $debug: Enables debug logging to a text file
  • $csv: Exports the results to a CSV file
  • $prompt: Enables interactive prompts for user confirmation
  • $maxPages: Controls the maximum number of pages to retrieve (default: 10)
  • $allPages: When set, retrieves all available pages without limitation

2. Documentation Header

The script includes comprehensive documentation:

  • Disclaimer about using at your own risk
  • Description: "Report on signins for tenant"
  • Source: GitHub Repository
  • Documentation: Wiki Link
  • Prerequisites: MS Graph PowerShell module installation required
  • Support: Author-provided contact info

3. Variable Initialization

Several variables are initialized:

  • Color-coding variables for message types:
    • $systemmessagecolor, $processmessagecolor, etc.
  • Output file path for CSV export:
    • $outputFile = "..\graph-signins.csv"

4. Debug Mode Setup

If the $debug parameter is set:

  • Creates a log file (graph-signins-get.txt) in the parent directory
  • Starts a transcript to capture all commands and outputs during execution

5. Authentication & Connection Logic

The script:

  • Clears the console and displays a start message
  • Connects to Microsoft Graph using Connect-MgGraph with scopes:
    • AuditLog.Read.All – Access to sign-in logs
    • Directory.Read.All – Access to directory information
  • Retrieves context of the connected session
  • Displays connected account info
  • If $prompt is set, asks for confirmation to proceed

6. Retry Logic Implementation

Includes custom Invoke-WithRetry function:

  • Accepts a script block to execute
  • Retries up to a specified number of times (default: 3)
  • Uses exponential backoff between attempts (2s initial, doubles each retry)
  • Aligns with Azure best practices for transient failure handling

7. Performance Measurement

The script:

  • Uses a stopwatch to measure total execution time
  • Tracks individual API call performance per page

8. API Query Construction

  • Sets Graph API endpoint for sign-in logs
  • Uses $select to retrieve specific fields:
    • clientAppUsed, ipAddress, isInteractive, userPrincipalName, createdDateTime, status
  • Limits result set to 100 records/page

9. Data Retrieval with Pagination

  • Initializes counters for pages and records
  • Loops until either:
    • No more pages
    • Max page limit is reached (unless $allPages is set)
  • For each page:
    • Measures retrieval time
    • Uses retry function for transient failures
    • Processes and formats results
    • Converts UTC to local time
    • Builds custom PowerShell objects
    • Gets next page URL

10. Date/Time Handling

  • Converts UTC timestamps to local time using:
    • DateTime.ParseExact with ISO 8601
    • InvariantCulture for region-independent parsing
    • Fallback and error handling for unparseable dates

11. Status Field Interpretation

  • Interprets each sign-in:
    • errorCode = 0Success
    • Otherwise → Failure with reason

12. Large Dataset Handling

  • For >1000 records:
    • Uses batch processing (max batch size: 5000)
    • Prevents memory issues

13. Results Display

  • Formats results in a table
  • Shows summary:
    • Total records retrieved
    • Number of pages processed
    • Total execution time

14. CSV Export

If $csv is set:

  • Exports dataset to specified file
  • Uses Export-Csv -NoTypeInformation for clean output

15. Cleanup

  • Displays completion message
  • If debug mode was enabled, stops transcript logging

Use Cases and Security Considerations

This script follows Azure best practices:

  • Authentication: Uses minimum required Graph scopes
  • Retry logic: Exponential backoff for stability
  • Error handling: Robust against failures
  • Performance: Efficient field selection and pagination
  • Large datasets: Optimized via batching

Ideal for:

  • Security audits & compliance reports
  • Detecting suspicious sign-ins
  • User access monitoring
  • Troubleshooting login issues

Note: Script does not store credentials. It uses secure, interactive authentication via Microsoft Graph PowerShell SDK.

Clone this wiki locally