⚡ PowerShell & Microsoft Graph Script Library

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.

8 scripts matching your filters · Browse guides with scripts →

PowerShell 7+Microsoft Graph SDK v2OAuth (M365 SaaS Engine skeleton via PHP endpoint)

Intune Windows PowerShell Script Assignment Reporter (Group Include/Exclusion & Built-in Targets)

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.

📖 Full guide: Intune PowerShell Script Group Exclusions & Built-In Targets
### FILE: README.md
# Intune Windows PowerShell Script Assignment Reporter

## What this repo does
This project inventories Intune **Windows PowerShell Script** assignments using **Microsoft Graph** and produces a CSV report that is suitable for audits and change reviews.

It resolves:
- Built-in include targets: **All Devices** / **All Users** (service release 2611 behavior)
- Included Entra groups and excluded Entra groups (group exclusions)

## Output
A CSV exported to the provided `ExportPath` containing one row per script assignment, with readable group names where possible.

## Components
- `src/Reporter.ps1`: Production-ready PowerShell script logic.
- `index.php`: M365 SaaS Engine-style endpoint skeleton that calls the PowerShell logic.

## Prerequisites
- Admin workstation
- PowerShell 7.x (Windows PowerShell 5.1 supported)
- Microsoft Graph PowerShell SDK v2 modules:
  - `Microsoft.Graph.Authentication`
  - `Microsoft.Graph.DeviceManagement`
  - `Microsoft.Graph.Groups`

## Required Graph Permissions
- `DeviceManagementConfiguration.Read.All`
- `Group.Read.All`

## Run (PowerShell)
```powershell
.
# Example
.\src\Reporter.ps1 -ExportPath .\Intune-WindowsPowerShellScriptAssignments.csv
```

## Run (SaaS)
Use the repository entrypoint `index.php` per your platform conventions.


### FILE: index.php
<?php
/**
 * M365 SaaS Engine endpoint skeleton
 *
 * This file demonstrates how to call Microsoft Graph (via the provided $ms->graphCall helper)
 * and then render UI cards (via render_premium_card).
 *
 * IMPORTANT:
 * - Actual execution of the inventory logic is implemented in PowerShell (src/Reporter.ps1)
 * - This endpoint can be adapted to trigger job execution in your SaaS environment.
 */

// You said: $ms is already initialized.
// You said: $accessToken is in $_SESSION['ms_access_token'].

// Defensive checks
session_start();
$accessToken = $_SESSION['ms_access_token'] ?? null;

if (!$accessToken) {
    http_response_code(401);
    echo json_encode(['error' => 'Missing ms_access_token in session']);
    exit;
}

$title = 'Intune Assignment Reporter';

// Example: quick health check call (count scripts). The full report generation is done in PowerShell.
$endpoint = 'https://graph.microsoft.com/beta/deviceManagement/deviceManagementScripts?$select=id,displayName';

try {
    $resp = $ms->graphCall($endpoint, $accessToken, 'GET', null);
    $count = isset($resp['value']) ? count($resp['value']) : 0;

    echo render_premium_card(
        'Discovered Intune Windows PowerShell scripts',
        (string)$count,
        null,
        'up',
        '📊',
        null
    );

    // In a real SaaS environment, you would enqueue / run src/Reporter.ps1 and return download links.
    // For now, return guidance.
    echo json_encode([
        'ok' => true,
        'scripts_discovered' => $count,
        'next' => 'Run src/Reporter.ps1 to export the full CSV report with include/exclude resolution.'
    ]);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}


### FILE: src/Reporter.ps1
#!/usr/bin/env pwsh
<#
.SYNOPSIS
Inventories Intune Windows PowerShell script assignments, resolving built-in include targets (All Devices/All Users) and group include/exclusion scopes.

.DESCRIPTION
This admin workstation script queries Microsoft Graph for Intune Windows PowerShell scripts (including their assignments), then builds an audit-ready CSV report.

The script understands Intune assignment targets including:
- Built-in include targets: All Devices / All Users (newer behavior aligned to Intune targeting model)
- Included groups (groupAssignmentTarget)
- Excluded groups (exclusionGroupAssignmentTarget)

It outputs a clean report with readable group display names when possible. It also implements throttling retry logic for Graph requests.

.EXAMPLE
.
# Export report to CSV
.\src\Reporter.ps1 -ExportPath .\Intune-WindowsPowerShellScriptAssignments.csv

.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
#>

[CmdletBinding(SupportsShouldProcess = $true)]
param(
    [Parameter(Mandatory = $false)]
    [ValidateNotNullOrEmpty()]
    [string]$ExportPath = '.\Intune-WindowsPowerShellScriptAssignments.csv',

    [Parameter(Mandatory = $false)]
    [switch]$IncludeRawAssignments,

    [Parameter(Mandatory = $false)]
    [switch]$PassThru
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

function Write-Log {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]$Message,

        [Parameter(Mandatory = $false)]
        [ValidateSet('INFO','WARN','ERROR','OK')]
        [string]$Level = 'INFO'
    )

    $timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
    switch ($Level) {
        'INFO'  { Write-Host "[$timestamp] [INFO ] $Message" -ForegroundColor Cyan }
        'WARN'  { Write-Host "[$timestamp] [WARN ] $Message" -ForegroundColor Yellow }
        'ERROR' { Write-Host "[$timestamp] [ERROR] $Message" -ForegroundColor Red }
        'OK'     { Write-Host "[$timestamp] [ OK  ] $Message" -ForegroundColor Green }
    }
}

function Test-MgModules {
    [CmdletBinding()]
    param()

    $requiredModules = @(
        'Microsoft.Graph.Authentication',
        'Microsoft.Graph.DeviceManagement',
        'Microsoft.Graph.Groups'
    )

    foreach ($module in $requiredModules) {
        if (-not (Get-Module -ListAvailable -Name $module)) {
            throw "Required module '$module' is not installed. Install-Module $module -Scope CurrentUser"
        }
    }
}

function Connect-GraphIfNeeded {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $false)]
        [string[]]$Scopes = @(
            'DeviceManagementConfiguration.Read.All',
            'Group.Read.All'
        )
    )

    $context = Get-MgContext -ErrorAction SilentlyContinue
    if (-not $context) {
        Write-Log -Message 'Connecting to Microsoft Graph...' -Level INFO
        Connect-MgGraph -Scopes $Scopes -NoWelcome | Out-Null
    }
    else {
        Write-Log -Message "Reusing existing Microsoft Graph context for tenant: $($context.TenantId)" -Level INFO
    }
}

function Invoke-GraphGetWithRetry {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]$Uri,

        [Parameter(Mandatory = $false)]
        [int]$MaxRetryCount = 5
    )

    $attempt = 0
    do {
        try {
            return Invoke-MgGraphRequest -Method GET -Uri $Uri -OutputType PSObject
        }
        catch {
            $attempt++
            $response = $_.Exception.Response
            $statusCode = $null
            $retryAfter = 5

            if ($response) {
                try { $statusCode = [int]$response.StatusCode } catch { $statusCode = $null }

                try {
                    if ($response.Headers -and $response.Headers.Contains('Retry-After')) {
                        $retryAfter = [int]$response.Headers.GetValues('Retry-After')[0]
                    }
                }
                catch {
                    $retryAfter = 5
                }
            }

            if ((($statusCode -eq 429) -or ($statusCode -eq 503)) -and $attempt -lt $MaxRetryCount) {
                Write-Log -Message "Graph throttling/service busy on '$Uri'. Retry $attempt of $MaxRetryCount in $retryAfter second(s)." -Level WARN
                Start-Sleep -Seconds $retryAfter
            }
            else {
                throw
            }
        }
    } while ($attempt -lt $MaxRetryCount)

    throw "Graph request failed after $MaxRetryCount attempts for URI: $Uri"
}

# Cache group display names to reduce Graph calls
$script:GroupNameCache = @{}

function Get-GroupDisplayNameSafe {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]$GroupId
    )

    if ([string]::IsNullOrWhiteSpace($GroupId)) {
        return ''
    }

    if ($script:GroupNameCache.ContainsKey($GroupId)) {
        return $script:GroupNameCache[$GroupId]
    }

    try {
        $group = Get-MgGroup -GroupId $GroupId -Property Id, DisplayName -ErrorAction Stop
        $script:GroupNameCache[$GroupId] = $group.DisplayName
        return $group.DisplayName
    }
    catch {
        Write-Log -Message "Failed to resolve group display name for GroupId '$GroupId'. Using raw ID." -Level WARN
        $script:GroupNameCache[$GroupId] = $GroupId
        return $GroupId
    }
}

function Resolve-AssignmentTarget {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [psobject]$AssignmentTarget
    )

    # The Graph SDK uses an odata.type marker under property '@odata.type'
    $odataType = $AssignmentTarget.'@odata.type'

    switch ($odataType) {
        '#microsoft.graph.allDevicesAssignmentTarget' {
            return [pscustomobject]@{
                TargetType   = 'Include'
                ScopeType    = 'BuiltIn'
                ScopeName    = 'All Devices'
                ScopeId      = 'BuiltIn-AllDevices'
                RawODataType = $odataType
            }
        }
        '#microsoft.graph.allLicensedUsersAssignmentTarget' {
            return [pscustomobject]@{
                TargetType   = 'Include'
                ScopeType    = 'BuiltIn'
                ScopeName    = 'All Users'
                ScopeId      = 'BuiltIn-AllUsers'
                RawODataType = $odataType
            }
        }
        '#microsoft.graph.groupAssignmentTarget' {
            $groupId = $AssignmentTarget.groupId
            return [pscustomobject]@{
                TargetType   = 'Include'
                ScopeType    = 'Group'
                ScopeName    = (Get-GroupDisplayNameSafe -GroupId $groupId)
                ScopeId      = $groupId
                RawODataType = $odataType
            }
        }
        '#microsoft.graph.exclusionGroupAssignmentTarget' {
            $groupId = $AssignmentTarget.groupId
            return [pscustomobject]@{
                TargetType   = 'Exclude'
                ScopeType    = 'Group'
                ScopeName    = (Get-GroupDisplayNameSafe -GroupId $groupId)
                ScopeId      = $groupId
                RawODataType = $odataType
            }
        }
🐙 GitHub
PowerShellAzure CLIMicrosoft GraphPHP

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.

📖 Full guide: Conquering AZ-104: A Senior Endpoint Architect's Blueprint for Azure Administra…
### 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
🐙 GitHub
PowerShellMicrosoft GraphPHP

Teams and Entra Conditional Access Automation

Scripts automate the deployment of Teams scam detection and Entra Conditional Access.

📖 Full guide: Enhancing Teams Security: Facilitator's Scam Detection Unveiled
### FILE: index.php
<?php 

session_start();
$accessToken = $_SESSION['ms_access_token'];

try {
    // Call to fetch current Conditional Access Policies
    $endpoint = '/identity/conditionalAccess/policies';
    $policies = $ms->graphCall($endpoint, $accessToken);
    
    foreach ($policies as $policy) {
        render_premium_card(
            $policy['displayName'],
            'Enabled: ' . ($policy['state'] == 'enabled' ? 'Yes' : 'No'),
            null, 'up', '🔐'
        );
    }
    
} catch (Exception $e) {
    echo 'Error fetching policies: ' . $e->getMessage();
}

?>

### FILE: scripts/EntraConditionalAccess.ps1
<#
.SYNOPSIS
   Configures a Conditional Access policy for enhanced security in Entra ID.
.DESCRIPTION
   This script connects to Microsoft Graph and creates a Conditional Access Policy for token protection.
.EXAMPLE
   .\EntraConditionalAccess.ps1
.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
#>

try {
    Connect-MgGraph -Scopes "Policy.ReadWrite.ConditionalAccess"
    
    $policy = @{
        displayName = "Entra Token Protection Policy"
        conditions   = @{
            users     = @{
                includeUsers = @( 'All' )
            }
        }
        grantControls = @{
            builtIns = @( 'bi_tokenProtection' )
        }
        state         = 'enabled'
    }
    
    New-MgConditionalAccessPolicy -BodyParameter $policy
    Write-Host "Conditional Access policy created successfully."
} catch {
    Write-Error "Failed to create policy: $_"
}
PowerShellMicrosoft GraphPHP

M365 & Intune Policy Automation for Junior Sysadmins

A GitHub repository demonstrating how to automate Intune policy assignments to dynamic Entra ID groups, integrated with an M365 SaaS engine.

📖 Full guide: The Modern Junior Sysadmin: What M365 & Intune Competencies Are Truly Expected?
### 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.

?>
🐙 GitHub
PowerShellMicrosoft GraphPHP

Identity and Access Automation

Automate user creation and governance with Microsoft Graph.

📖 Full guide: Mastering the Microsoft Identity and Access Administrator Certification with Pr…
### 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
🐙 GitHub
PowerShellMicrosoft GraphPHP

Azure Administrator M365 Integration

PowerShell module for Azure and Microsoft 365 automation integration.

📖 Full guide: AZ-104 with 875: Azure Admin Strategy for Identity & Governance
### FILE: index.php
<?php 
// Logic to fetch data from Graph and call render_premium_card multiple times to build the dashboard...
$endpoint = 'https://graph.microsoft.com/v1.0/identity/conditionalAccess/policies';
$accessToken = $_SESSION['ms_access_token'];
$response = $ms->graphCall($endpoint, $accessToken);

render_premium_card('Conditional Access Policies', 'Summary', count($response['value']));
// Additional cards can be rendered similarly...
?>

### FILE: scripts/Automation.ps1
<#
.SYNOPSIS
    PowerShell script to audit and automate Azure and Microsoft 365 integrations.

.DESCRIPTION
    This script connects to Microsoft Graph, audits custom RBAC roles, validates managed identity federation, and inspects diagnostic settings on storage accounts.

.EXAMPLE
    .\Automation.ps1 -SubscriptionId '00000000-0000-0000-0000-000000000000' -ResourceGroupName 'myResourceGroup' -StorageAccountName 'myStorageAccount'

.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
#>

#Requires -Version 7.2
#Requires -Modules Microsoft.Graph.Authentication, Microsoft.Graph.Identity.Governance

[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')]
param(
    [Parameter(Mandatory)]
    [ValidatePattern('^[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}$')]
    [string]$SubscriptionId,

    [Parameter(Mandatory)]
    [string]$ResourceGroupName,

    [Parameter(Mandatory)]
    [string]$StorageAccountName
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

# ── 1. Connect to Microsoft Graph (required scopes) ──────────────────────────
$requiredScopes = @(
    'RoleManagement.Read.Directory',
    'Directory.Read.All',
    'Policy.Read.All'
)

try {
    Write-Host "[INFO] Connecting to Microsoft Graph..." -ForegroundColor Cyan
    Connect-MgGraph -Scopes $requiredScopes -NoWelcome
    $context = Get-MgContext
    Write-Host "[OK]   Connected as: $($context.Account) | TenantId: $($context.TenantId)" `
        -ForegroundColor Green
}
catch {
    Write-Error "[FATAL] Graph connection failed: $_"
    exit 1
}

# ── 2. Enumerate Custom RBAC Roles scoped to Resource Group ──────────────────
Write-Host "`n[DOMAIN: Identity & Governance] Auditing custom RBAC role assignments..." `
    -ForegroundColor Magenta

$rgScope = "/subscriptions/$SubscriptionId/resourceGroups/$ResourceGroupName"

try {
    # Using Invoke-MgGraphRequest for ARM endpoint — Graph doesn't expose ARM RBAC
    $armToken = (Get-MgContext).AccessToken
    $armHeaders = @{ Authorization = "Bearer $armToken"; 'Content-Type' = 'application/json' }

    $assignmentsUri = "https://management.azure.com$($rgScope)/providers/" +
        "Microsoft.Authorization/roleAssignments?api-version=2022-04-01"

    $assignments = Invoke-RestMethod -Method GET -Uri $assignmentsUri `
        -Headers $armHeaders

    $customAssignments = $assignments.value | Where-Object {
        $_.properties.roleDefinitionId -notmatch `
            '/providers/Microsoft.Authorization/roleDefinitions/[a-f0-9-]{36}'
    }

    Write-Host "[OK]   Total assignments on $ResourceGroupName : $($assignments.value.Count)"
    Write-Host "[INFO] Assignments referencing custom role definitions: $($customAssignments.Count)"

    foreach ($a in $assignments.value) {
        $roleDefId = $a.properties.roleDefinitionId.Split('/')[-1]
        $roleDef = Invoke-RestMethod -Method GET `
            -Uri "https://management.azure.com/subscriptions/$SubscriptionId/providers/Microsoft.Authorization/roleDefinitions/$($roleDefId)?api-version=2022-04-01" `
            -Headers $armHeaders
        
        $isCustom = $roleDef.properties.type -eq 'CustomRole'
        $customTag = if ($isCustom) { "[CUSTOM]" } else { "[BUILTIN]" }
        Write-Host "  $customTag $($roleDef.properties.roleName) → $($a.properties.principalId)"
    }
}
catch {
    Write-Warning "[WARN] RBAC enumeration failed: $_"
}

# ── 3. Validate Managed Identity Federation Status ────────────────────────────
Write-Host "`n[DOMAIN: Identity & Governance] Checking User-Assigned Managed Identities..." `
    -ForegroundColor Magenta

try {
    # Query Graph for Service Principals with ServicePrincipalType = ManagedIdentity
    $miFilter = "servicePrincipalType eq 'ManagedIdentity'"
    $managedIdentities = Invoke-MgGraphRequest -Method GET `
        -Uri "https://graph.microsoft.com/v1.0/servicePrincipals?`$filter=$miFilter&`$select=id,displayName,servicePrincipalType,appId"

    Write-Host "[OK]   Managed Identity Service Principals found: $($managedIdentities.value.Count)"

    foreach ($mi in $managedIdentities.value) {
        # Check federated identity credentials (AZ-104 objective: OIDC federation)
        $fedCreds = Invoke-MgGraphRequest -Method GET `
            -Uri "https://graph.microsoft.com/v1.0/servicePrincipals/$($mi.id)/federatedIdentityCredentials"

        $fedCount = $fedCreds.value.Count
        $fedStatus = if ($fedCount -gt 0) { "[$fedCount federated credentials]" } else { "[No federation]" }
        Write-Host "  MI: $($mi.displayName) | AppId: $($mi.appId) $fedStatus"
    }
}
catch {
    Write-Warning "[WARN] Managed Identity query failed: $_"
}

# ── 4. Validate Diagnostic Settings on Storage Account ───────────────────────
Write-Host "`n[DOMAIN: Monitor] Validating Diagnostic Settings on Storage Account..." `
    -ForegroundColor Magenta

try {
    $storageResourceId = "/subscriptions/$SubscriptionId/resourceGroups/$ResourceGroupName" +
        "/providers/Microsoft.Storage/storageAccounts/$StorageAccountName"

    $diagUri = "https://management.azure.com$($storageResourceId)" +
        "/providers/microsoft.insights/diagnosticSettings?api-version=2021-05-01-preview"

    $diagSettings = Invoke-RestMethod -Method GET -Uri $diagUri -Headers $armHeaders

    if ($diagSettings.value.Count -eq 0) {
        Write-Warning "[WARN] No diagnostic settings configured on $StorageAccountName"
        Write-Warning "       AZ-104 Objective: Configure Azure Monitor diagnostic settings"
    }
    else {
        foreach ($ds in $diagSettings.value) {
            $sink = if ($ds.properties.workspaceId) { "Log Analytics" } `
                    elseif ($ds.properties.storageAccountId) { "Storage" } `
                    elseif ($ds.properties.eventHubAuthorizationRuleId) { "Event Hub" } `
                    else { "Unknown" }
            Write-Host "[OK]   DiagSetting: '$($ds.name)' → Sink: $sink"
        }
    }
}
catch {
    Write-Warning "[WARN] Diagnostic settings check failed: $_"
}

# ── 5. Conditional Access Policy Inventory (Governance cross-check) ──────────
Write-Host "`n[DOMAIN: Identity & Governance] Enumerating Conditional Access Policies..." `
    -ForegroundColor Magenta

if ($PSCmdlet.ShouldProcess("Entra ID Tenant", "Read Conditional Access Policies")) {
    try {
        $caPolicies = Invoke-MgGraphRequest -Method GET `
            -Uri "https://graph.microsoft.com/v1.0/identity/conditionalAccess/policies?`$select=displayName,state,conditions,grantControls"

        $enabledCount  = ($caPolicies.value | Where-Object { $_.state -eq 'enabled' }).Count
        $reportOnly    = ($caPolicies.value | Where-Object { $_.state -eq 'enabledForReportingButNotEnforced' }).Count
        $disabledCount = ($caPolicies.value | Where-Object { $_.state -eq 'disabled' }).Count

        Write-Host "[OK]   CA Policies — Enabled: $enabledCount | Report-Only: $reportOnly | Disabled: $disabledCount"
    }
    catch {
        Write-Warning "[WARN] Conditional Access read failed (check Policy.Read.All scope): $_"
    }
}

Write-Host "`n[COMPLETE] AZ-104 Lab Validation finished." -ForegroundColor Green
exit 0
🐙 GitHub
PowerShellMicrosoft GraphExchange Online ManagementPHP

Exchange Online EWS Retirement Toolkit - Discovery, Whitelist Containment & Phased Cutover

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.

📖 Full guide: Exchange Online EWS Retirement 2026: EwsEnabled & EwsAllowedAppIDs Enforcement …
### FILE: README.md
# Exchange Online EWS Retirement Toolkit

## Overview
October 2026 marks a hard authentication cutoff for EWS in Exchange Online. This toolkit implements the full discovery-to-remediation playbook:

1. **Baseline** — audit org-wide and per-mailbox EWS configuration.
2. **Discovery** — pull 12 months of `EwsConnect` Unified Audit Log events.
3. **Correlation** — resolve `ClientAppId` GUIDs to Entra ID app registrations, owners, and secret/cert expiration.
4. **Containment** — manage `EwsAllowedAppIDs` as a time-boxed whitelist with remediation tickets.
5. **Phased Cutover** — flip mailbox-level `EwsEnabled` by cohort, validate, then lock down org-wide.
6. **Dashboard** — an M365 SaaS Engine dashboard (PHP) surfacing discovery metrics via Microsoft Graph.

## Structure
```
scripts/
  1-Get-EwsBaselineConfig.ps1
  2-Export-EwsConnectAuditLogs.ps1
  3-Resolve-EwsClientAppIds.ps1
  4-Manage-EwsAllowedAppIDsWhitelist.ps1
  5-Set-EwsMailboxCohortCutover.ps1
  6-Invoke-EwsOrgWideLockdown.ps1
src/
  index.php
  includes/graph_helpers.php
```

## Required Scopes / Roles
- Entra ID App/Delegated: `Exchange.ManageAsApp`, `AuditLog.Read.All`, `Application.Read.All`
- Exchange Online Role: `View-Only Organization Management` (discovery) / `Organization Management` (remediation)

## Author
**Souhaiel Morhag** — [MSEndpoint.com](https://msendpoint.com) | [Academy](https://app.msendpoint.com/academy) | [LinkedIn](https://linkedin.com/in/souhaiel-morhag) | [GitHub](https://github.com/Msendpoint)


### FILE: scripts/1-Get-EwsBaselineConfig.ps1
<#
.SYNOPSIS
    Baselines the current Exchange Online EWS configuration at the org-wide and per-mailbox level.

.DESCRIPTION
    Connects to Exchange Online and reports on the org-wide EwsEnabled default (Get-OrganizationConfig),
    the current EwsAllowedAppIDs whitelist, and a per-mailbox export of EwsEnabled overrides via
    Get-CASMailbox. Use this as the mandatory first step of the EWS retirement playbook before
    making any containment or cutover changes. Exports results to CSV for audit trail purposes.

.EXAMPLE
    .\1-Get-EwsBaselineConfig.ps1 -OutputPath "C:\EwsAudit\Baseline"

    Connects to Exchange Online, pulls org-wide and per-mailbox EWS settings, and writes
    OrgConfig-Baseline.csv and MailboxEws-Baseline.csv to the specified folder.

.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
#>

[CmdletBinding()]
param(
    [Parameter(Mandatory = $false)]
    [string]$OutputPath = ".\EwsBaseline"
)

begin {
    if (-not (Test-Path -Path $OutputPath)) {
        New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null
    }

    if (-not (Get-Module -Name ExchangeOnlineManagement -ListAvailable)) {
        throw "ExchangeOnlineManagement module is required. Install it via: Install-Module ExchangeOnlineManagement"
    }
}

process {
    try {
        Write-Host "Connecting to Exchange Online..." -ForegroundColor Cyan
        Connect-ExchangeOnline -ShowBanner:$false -ErrorAction Stop

        Write-Host "Retrieving org-wide EWS configuration..." -ForegroundColor Cyan
        $orgConfig = Get-OrganizationConfig -ErrorAction Stop |
            Select-Object Identity, EwsEnabled, EwsAllowedAppIDs, EwsApplicationAccessPolicy

        $orgConfigPath = Join-Path -Path $OutputPath -ChildPath "OrgConfig-Baseline.csv"
        $orgConfig | Export-Csv -Path $orgConfigPath -NoTypeInformation -Encoding UTF8
        Write-Host "Org-wide config exported to: $orgConfigPath" -ForegroundColor Green

        if ($orgConfig.EwsEnabled -eq $true -and [string]::IsNullOrEmpty($orgConfig.EwsAllowedAppIDs)) {
            Write-Warning "Org-wide EwsEnabled = TRUE with NO EwsAllowedAppIDs whitelist. Every registered app with a valid OAuth token can currently reach every mailbox via EWS."
        }

        Write-Host "Retrieving per-mailbox EWS overrides (this may take a while at scale)..." -ForegroundColor Cyan
        $mailboxes = Get-CASMailbox -ResultSize Unlimited -ErrorAction Stop |
            Select-Object Identity, PrimarySmtpAddress, EwsEnabled, EwsAllowedAppIDs

        $mailboxPath = Join-Path -Path $OutputPath -ChildPath "MailboxEws-Baseline.csv"
        $mailboxes | Export-Csv -Path $mailboxPath -NoTypeInformation -Encoding UTF8
        Write-Host "Per-mailbox EWS baseline exported to: $mailboxPath" -ForegroundColor Green

        $summary = [PSCustomObject]@{
            TotalMailboxes            = $mailboxes.Count
            MailboxesWithEwsExplicitlyDisabled = ($mailboxes | Where-Object { $_.EwsEnabled -eq $false }).Count
            MailboxesWithNoOverride   = ($mailboxes | Where-Object { $null -eq $_.EwsEnabled }).Count
            OrgWideEwsEnabled         = $orgConfig.EwsEnabled
            OrgWideWhitelistCount     = ($orgConfig.EwsAllowedAppIDs | Measure-Object).Count
        }

        Write-Host "`n--- Baseline Summary ---" -ForegroundColor Yellow
        $summary | Format-List
    }
    catch {
        Write-Error "Baseline collection failed: $($_.Exception.Message)"
        throw
    }
    finally {
        Disconnect-ExchangeOnline -Confirm:$false -ErrorAction SilentlyContinue
    }
}
🐙 GitHub
PowerShellMicrosoft Graph

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.

📖 Full guide: Microsoft Entra Backup and Recovery: Production Guide
<#
.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
🐙 GitHub
📡 New scripts every week

Get new remediation scripts and the Weekly TV digest in your inbox.

Subscribe free →

⚠️ Always review and test scripts in a pilot group before production use. Scripts are provided as-is under the terms of each GitHub repository.