Streamlining System Health Checks Using PowerShell for M365

Maintaining the health of your M365 environment is essential to ensure optimal performance and security. Regular system health checks can help identify potential issues before they escalate. This PowerShell script automates the process of checking important health metrics for your M365 services, providing administrators with a clear overview of the system’s status.
This script will:
1. Check the status of key services in M365.
2. Retrieve the last sign-in activities of users.
3. Report any critical issues that might need immediate attention.
By running this script, IT professionals can efficiently monitor their M365 environment and ensure that users have a seamless experience.

# Connect to Microsoft Graph
Connect-MgGraph -Scopes 'AuditLog.Read.All', 'Directory.Read.All'
# Check the status of essential M365 services
$serviceStatus = Get-MgServiceHealth
Write-Host "=== M365 Service Health Status ==="
foreach ($service in $serviceStatus) {
    Write-Host "Service: $($service.ServiceArea) - Status: $($service.Status)"
}
# Retrieve last sign-in activity for users
$lastSignIns = Get-MgUserSignIn -Top 10
Write-Host "=== Recent User Sign-Ins ==="
foreach ($signIn in $lastSignIns) {
    Write-Host "User: $($signIn.UserPrincipalName) - Last Sign-In: $($signIn.CreatedDateTime)"
}
# Perform additional checks or alerts for critical issues
# You can customize the conditions here based on your requirements
$criticalIssues = $serviceStatus | Where-Object { $_.Status -ne "ServiceHealthy" }
if ($criticalIssues) {
    Write-Host "*** Critical Issues Detected ***"
    foreach ($issue in $criticalIssues) {
        Write-Host "Issue in service: $($issue.ServiceArea) - Current Status: $($issue.Status)"
    }
} else {
    Write-Host "All services are operating normally."
}
# Disconnect from Microsoft Graph
Disconnect-MgGraph
Write-Host "Health check completed."