39 production-tested scripts for Intune, Entra ID, Exchange Online and Windows — detection & remediation pairs, Graph automations and reporting tools. Every script links to the full guide that explains when (and when not) to run it.
Exports a tenant report of Intune Windows PowerShell script assignments, resolving built-in targets (All Devices/All Users) and included/excluded Entra groups for audit-ready change reviews.
AZ-104 Endpoint Architect's Blueprint for Azure & M365 Automation
A GitHub repository for Azure administration and M365 automation, focusing on endpoint architect needs, featuring a PowerShell script for secure Azure infrastructure deployment and a PHP-based M365 SaaS engine frontend.
### FILE: index.php
<?php
// This is a placeholder for the M365 SaaS Engine frontend dashboard.
// It demonstrates how to fetch data from Microsoft Graph and render it using the provided functions.
// In a real application, more sophisticated logic, error handling, and UI components would be present.
// Assume $ms (Microsoft Graph service-architect-automation
### FILE: index.php
<?php
// This file serves as the main dashboard for the M365 SaaS engine.
// It orchestrates calls to Microsoft Graph via the provided $ms object and renders UI cards.
// Ensure the user is authenticated and has an access token.
if (!isset($_SESSION['ms_access_token'])) {
// Redirect to login or show an error
die('Authentication required. Please log in.');
}
$accessToken = $_SESSION['ms_access_token'];
// --- Example 1: Fetching Intune Device Compliance Policies ---
$policyEndpoint = '/deviceManagement/deviceCompliancePolicies';
$policiesData = $ms->graphCall($policyEndpoint, $accessToken);
if (isset($policiesData['value']) && is_array($policiesData['value'])) {
$activePolicies = count($policiesData['value']);
render_premium_card(
'Active Intune Policies',
(string)$activePolicies,
null, // No trend value for this example
'up', // Assume 'up' is good for policy count
'🛡️'
);
} else {
render_premium_card('Active Intune Policies', 'N/A', null, 'down', '⚠️');
error_log('Failed to fetch Intune policies: ' . json_encode($policiesData));
}
// --- Example 2: Fetching Dynamic Device Groups ---
$groupEndpoint = '/groups?$filter=groupTypes/any(c:c eq \'DynamicMembership\')';
$groupsData = $ms->graphCall($groupEndpoint, $accessToken);
if (isset($groupsData['value']) && is_array($groupsData['value'])) {
$dynamicGroups = count($groupsData['value']);
render_premium_card(
'Dynamic Device Groups',
(string)$dynamicGroups,
null,
'up',
'👥'
);
} else {
render_premium_card('Dynamic Device Groups', 'N/A', null, 'down', '⚠️');
error_log('Failed to fetch dynamic groups: ' . json_encode($groupsData));
}
// --- Example 3: Displaying Recent Sign-in Failures (Placeholder) ---
// In a real scenario, you would query Entra ID sign-in logs via Graph.
// For demonstration, let's simulate some data or fetch a simplified view.
// $signInLogsEndpoint = '/auditLogs/signIns?$filter=status/errorCode ne 0&$top=5';
// $failedSignIns = $ms->graphCall($signInLogsEndpoint, $accessToken);
// For this example, let's use a static card.
render_premium_card(
'Recent Sign-in Failures',
'5',
'20% increase',
'down',
'❌'
);
// --- Integration with PowerShell Automation (Conceptual) ---
// If a user clicks a button to 'Assign Policy', the PHP backend would:
// 1. Validate input.
// 2. Potentially call the PowerShell script (e.g., via a system call or Azure Function).
// 3. Or, directly make the Graph API call for assignment using $ms->graphCall and a POST method.
// Example: $ms->graphCall("/deviceManagement/deviceCompliancePolicies/{policyId}/assignments", $accessToken, 'POST', $assignmentBody);
// The PowerShell script 'Assign-IntunePolicyToDynamicGroup.ps1' would represent a backend automation
// that could be triggered by such a PHP interface or run on a schedule.
?>
### FILE: index.php
<?php
// Logic to fetch data from Graph and call render_premium_card multiple times to build the dashboard...
$accessToken = $_SESSION['ms_access_token'];
$userEndpoint = 'https://graph.microsoft.com/v1.0/users';
$response = $ms->graphCall($userEndpoint, $accessToken);
// Render cards based on response data
render_premium_card('User Creation', count($response['value']), 'Up', 'up', '👤', 70);
?>
### FILE: scripts/Automation.ps1
<#
.SYNOPSIS
Automates user creation and role assignment using Microsoft Graph API.
.DESCRIPTION
This script creates a user in Azure AD with the given UserPrincipalName, DisplayName, and assigns a role if specified using the Microsoft Graph PowerShell module.
.EXAMPLE
.
param (
[string]$UserPrincipalName = 'jdoe@example.com',
[string]$DisplayName = 'John Doe',
[string]$Role = 'User'
)
.NOTES
Author: Souhaiel Morhag
Company: MSEndpoint.com
Blog: https://msendpoint.com
Academy: https://app.msendpoint.com/academy
LinkedIn: https://linkedin.com/in/souhaiel-morhag
GitHub: https://github.com/Msendpoint
License: MIT
#>
param (
[string]$UserPrincipalName,
[string]$DisplayName,
[string]$Role
)
Try {
Write-Output "Creating user $UserPrincipalName"
$user = @{
"UserPrincipalName" = $UserPrincipalName
"DisplayName" = $DisplayName
"MailNickname" = $UserPrincipalName.Split('@')[0]
"AccountEnabled" = $true
}
New-MgUser -BodyParameter $user
Write-Output "User $UserPrincipalName created successfully"
If ($Role) {
Write-Output "Assigning role $Role to $UserPrincipalName"
# Add role assignment logic here
}
} Catch {
Write-Output "Failed to create user: $_"
exit 1
}
exit 0
A PowerShell and M365 SaaS toolkit to discover EWS-dependent applications, correlate audit logs against Entra ID app registrations, manage EwsAllowedAppIDs containment, and execute a phased mailbox-level EWS cutover ahead of the October 2026 retirement.
Entra Conditional Access Policy Backup via Microsoft Graph
Exports all Microsoft Entra ID Conditional Access policies to a versioned JSON file for backup, audit, and recovery purposes using the Microsoft Graph PowerShell SDK.
<#
.SYNOPSIS
Exports all Microsoft Entra ID Conditional Access policies to a timestamped JSON backup file.
.DESCRIPTION
This script connects to Microsoft Graph using the Policy.Read.All and
Policy.ReadWrite.ConditionalAccess scopes, retrieves all Conditional Access
policies defined in the tenant, and exports them as a formatted JSON file.
The output file is named with a UTC timestamp to support versioned, point-in-time
backups. This script is intended to be used as a scheduled backup mechanism or
as a secondary validation layer alongside Microsoft Entra's native Backup and
Recovery feature.
Use cases include:
- Pre-change snapshots before modifying Conditional Access policies
- Scheduled nightly backups stored in source control (e.g., Git)
- Audit evidence for ISO 27001, SOC 2, or NIST CSF compliance reviews
- Recovery baseline when manual policy reconstruction is required
Requirements:
- PowerShell 7.x or Windows PowerShell 5.1
- Microsoft.Graph.Identity.SignIns module installed
- Entra ID P2, E5, or Entra Suite license (for full CA policy access)
- Sufficient permissions: Policy.Read.All (minimum); Policy.ReadWrite.ConditionalAccess if restores are planned
.NOTES
Author: Souhaiel Morhag
Company: MSEndpoint.com
Blog: https://msendpoint.com
Academy: https://app.msendpoint.com/academy
LinkedIn: https://linkedin.com/in/souhaiel-morhag
GitHub: https://github.com/Msendpoint
License: MIT
.EXAMPLE
# Run interactively with default output directory (script root)
.\Backup-EntraConditionalAccessPolicies.ps1
.EXAMPLE
# Specify a custom output directory
.\Backup-EntraConditionalAccessPolicies.ps1 -OutputPath 'C:\Backups\EntraCA'
.EXAMPLE
# Run non-interactively using a Managed Identity or pre-authenticated session
Connect-MgGraph -Identity
.\Backup-EntraConditionalAccessPolicies.ps1 -OutputPath 'D:\CABackups' -SkipConnect
#>
[CmdletBinding()]
param (
# Directory where the JSON backup file will be saved. Defaults to the script's own directory.
[Parameter(Mandatory = $false)]
[string]$OutputPath = $PSScriptRoot,
# Skip the Connect-MgGraph call if a session is already established (e.g., in automation pipelines).
[Parameter(Mandatory = $false)]
[switch]$SkipConnect
)
#region --- Prerequisites Check ---
# Ensure the required Graph module is available
if (-not (Get-Module -ListAvailable -Name 'Microsoft.Graph.Identity.SignIns')) {
Write-Error "Required module 'Microsoft.Graph.Identity.SignIns' is not installed. Run: Install-Module Microsoft.Graph.Identity.SignIns -Scope CurrentUser"
exit 1
}
# Import the module (suppress verbose output)
Import-Module Microsoft.Graph.Identity.SignIns -ErrorAction Stop
#endregion
#region --- Authentication ---
if (-not $SkipConnect) {
try {
Write-Verbose "Connecting to Microsoft Graph..."
# Request minimum required scopes for reading CA policies
Connect-MgGraph -Scopes "Policy.Read.All", "Policy.ReadWrite.ConditionalAccess" -ErrorAction Stop
Write-Verbose "Successfully connected to Microsoft Graph."
}
catch {
Write-Error "Failed to connect to Microsoft Graph. Error: $_"
exit 1
}
}
else {
Write-Verbose "Skipping Connect-MgGraph as -SkipConnect was specified."
# Validate that an active Graph session already exists
$context = Get-MgContext
if (-not $context) {
Write-Error "No active Microsoft Graph session found. Either remove -SkipConnect or authenticate first using Connect-MgGraph."
exit 1
}
Write-Verbose "Using existing Graph session for tenant: $($context.TenantId)"
}
#endregion
#region --- Output Directory Validation ---
try {
if (-not (Test-Path -Path $OutputPath)) {
Write-Verbose "Output directory does not exist. Creating: $OutputPath"
New-Item -ItemType Directory -Path $OutputPath -Force | Out-Null
}
}
catch {
Write-Error "Failed to create or access output directory '$OutputPath'. Error: $_"
exit 1
}
#endregion
#region --- Export Conditional Access Policies ---
try {
Write-Verbose "Retrieving all Conditional Access policies from Microsoft Graph..."
# Retrieve all CA policies; -All ensures pagination is handled automatically
$policies = Get-MgIdentityConditionalAccessPolicy -All -ErrorAction Stop
if (-not $policies -or $policies.Count -eq 0) {
Write-Warning "No Conditional Access policies found in the tenant. The backup file will be empty."
}
else {
Write-Verbose "Retrieved $($policies.Count) Conditional Access policy/policies."
}
}
catch {
Write-Error "Failed to retrieve Conditional Access policies. Error: $_"
exit 1
}
#endregion
#region --- Serialize and Write to File ---
try {
# Build a timestamped filename for versioned backups (UTC to avoid timezone ambiguity)
$timestamp = (Get-Date).ToUniversalTime().ToString('yyyyMMdd_HHmmss')
$outputFile = Join-Path -Path $OutputPath -ChildPath "ConditionalAccessPolicies_$timestamp`_UTC.json"
Write-Verbose "Serializing policies to JSON..."
# Convert to JSON with sufficient depth to capture nested conditions (e.g., grantControls, sessionControls)
$jsonContent = $policies | ConvertTo-Json -Depth 20 -ErrorAction Stop
# Write UTF-8 encoded file without BOM for compatibility with Git and downstream tools
[System.IO.File]::WriteAllText($outputFile, $jsonContent, [System.Text.UTF8Encoding]::new($false))
Write-Host "Backup complete." -ForegroundColor Green
Write-Host " Policies exported : $($policies.Count)" -ForegroundColor Cyan
Write-Host " Output file : $outputFile" -ForegroundColor Cyan
Write-Host " Timestamp (UTC) : $timestamp" -ForegroundColor Cyan
}
catch {
Write-Error "Failed to serialize or write the backup file. Error: $_"
exit 1
}
#endregion
#region --- Disconnect (optional, skip in automation contexts) ---
if (-not $SkipConnect) {
try {
Disconnect-MgGraph -ErrorAction SilentlyContinue
Write-Verbose "Disconnected from Microsoft Graph."
}
catch {
Write-Warning "Could not cleanly disconnect from Microsoft Graph: $_"
}
}
#endregion