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

31 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 GraphIntune

Intune Device Compliance & Health Auditor

Automated PowerShell script utilizing Microsoft Graph v2 SDK to audit endpoint compliance states, hardware metrics, and synchronization health across Microsoft Intune fleets.

📖 Full guide: Successfully Transitioning from MS-102 to MD-102: Intune Focused Strategies
<#
.SYNOPSIS
   Automated Intune Device Compliance and Health Auditor.

.DESCRIPTION
   Audits Microsoft Intune enrolled endpoints using Microsoft Graph PowerShell SDK v2.
   Checks compliance states, operating system versions, and sync intervals to enforce Zero Trust hygiene.

.PARAMETER ComplianceFilter
   Filter by compliance status: All, Compliant, Noncompliant, or InGracePeriod. Default: Noncompliant.

.PARAMETER Top
   Maximum number of records to retrieve. Default: 100.

.EXAMPLE
   .\Test-IntuneDeviceReadiness.ps1 -ComplianceFilter Noncompliant

.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)]
    [ValidateSet('All', 'Compliant', 'Noncompliant', 'InGracePeriod')]
    [string]$ComplianceFilter = 'Noncompliant',

    [Parameter(Mandatory = $false)]
    [int]$Top = 100
)

Begin {
    Write-Host "[INIT] Verifying Microsoft Graph Authentication context..." -ForegroundColor Cyan
    try {
        $context = Get-MgContext -ErrorAction Stop
        if (-not $context) {
            throw "No active Graph session detected. Run 'Connect-MgGraph -Scopes DeviceManagementManagedDevices.Read.All'"
        }
        Write-Host "  -> Connected to Tenant ID: $($context.TenantId)" -ForegroundColor Green
    }
    catch {
        Write-Error "Authentication failure: $_"
        exit 1
    }
}

Process {
    Write-Host "[QUERY] Fetching managed endpoints (Filter: $ComplianceFilter)..." -ForegroundColor Cyan
    
    $filterExpression = $null
    if ($ComplianceFilter -ne 'All') {
        $filterExpression = "complianceState eq '$($ComplianceFilter.ToLower())'"
    }

    try {
        $params = @{
            Property = @(
                'id', 'deviceName', 'operatingSystem', 'osVersion', 
                'complianceState', 'userPrincipalName', 'lastSyncDateTime',
                'enrolledDateTime', 'serialNumber', 'manufacturer', 'model'
            )
            Top = $Top
        }

        if ($filterExpression) {
            $params['Filter'] = $filterExpression
        }

        $devices = Get-MgDeviceManagementManagedDevice @params -ErrorAction Stop

        if (-not $devices -or $devices.Count -eq 0) {
            Write-Host "  -> No devices matched criteria '$ComplianceFilter'." -ForegroundColor Yellow
            return
        }

        Write-Host "  -> Retrieved $($devices.Count) device records. Analyzing compliance telemetry..." -ForegroundColor Green

        $report = foreach ($dev in $devices) {
            [PSCustomObject]@{
                DeviceId         = $dev.Id
                DeviceName       = $dev.DeviceName
                PrimaryUser      = $dev.UserPrincipalName
                OS               = "$($dev.OperatingSystem) ($($dev.OsVersion))"
                Hardware         = "$($dev.Manufacturer) $($dev.Model)"
                ComplianceState  = $dev.ComplianceState
                LastSyncUTC      = $dev.LastSyncDateTime
                DaysSinceSync    = if ($dev.LastSyncDateTime) { [math]::Round(((Get-Date) - $dev.LastSyncDateTime).TotalDays, 1) } else { 'N/A' }
            }
        }

        $report | Format-Table -AutoSize
        return $report
    }
    catch {
        Write-Error "Failed to retrieve Intune device inventory: $_"
        exit 1
    }
}
🐙 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

Azure Subscription Automator

Automates listing of Azure subscriptions using Microsoft Graph

📖 Full guide: Kickstart Your Azure Journey: Master the AZ-900 Certification for Cloud Success
### FILE: index.php
<?php

session_start();

// Check if access token is available
if (!isset($_SESSION['ms_access_token'])) {
    exit('Access token is missing. Please authenticate first.');
}

$accessToken = $_SESSION['ms_access_token'];

// Fetch subscriptions from Microsoft Graph
try {
    $endpoint = '/subscriptions';
    $response = $ms->graphCall($endpoint, $accessToken);
    $subscriptions = json_decode($response);

    foreach ($subscriptions->value as $subscription) {
        render_premium_card(
            'Subscription', 
            "ID: {$subscription->id}, Name: {$subscription->displayName}", 
            null, 
            'neutral', 
            '📄'
        );
    }
} catch (Exception $e) {
    echo "Error fetching subscriptions: " . $e->getMessage();
}

?>

### FILE: scripts/Automation.ps1
<#
.SYNOPSIS
   Lists Azure subscriptions using Microsoft Graph.

.DESCRIPTION
   This script connects to Microsoft Graph using client credentials and lists all Azure subscriptions.
   It ensures error handling and disconnects from Graph after execution.

.EXAMPLE
   .\Automation.ps1 -TenantId '<TENANT_ID>' -ClientId '<CLIENT_ID>' -ClientSecret '<CLIENT_SECRET>'

.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]$TenantId,
    [string]$ClientId,
    [string]$ClientSecret
)

Import-Module Microsoft.Graph

Try {
    # Connect to Microsoft Graph
    Connect-MgGraph -ClientId $ClientId -TenantId $TenantId -ClientSecret $ClientSecret
    
    # Retrieve and list subscriptions
    $subscriptions = Get-MgSubscription 
    if ($subscriptions) {
        foreach ($subscription in $subscriptions) {
            Write-Output ("ID: $($subscription.Id), Name: $($subscription.DisplayName)")
        }
    }
} Catch {
    Write-Error "Error: $($_.Exception.Message)"
    exit 1
} Finally {
    # Disconnect from Graph
    Disconnect-MgGraph
    exit 0
}
🐙 GitHub
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

Intune Enterprise Fleet Triage & Sync Engine

An enterprise-grade modern endpoint diagnostics and synchronization framework designed to bridge the gap between OMA-DM and IME execution states.

📖 Full guide: The Architect's Blueprint: Essential Resources for Mastering MD-102 & Modern En…
### FILE: index.php
<?php
/**
 * Intune Enterprise Fleet Triage Dashboard
 * 
 * Translates modern endpoint telemetry and dual-channel agent state analysis
 * from raw Graph API transactions into a high-fidelity administrative dashboard.
 */

$accessToken = $_SESSION['ms_access_token'] ?? null;
if (!$accessToken) {
    echo "<div class='alert alert-danger'>Authentication Context Lost. Please log in to Microsoft 365.</div>";
    return;
}

// Configuration parameters matching architectural defaults
$deviceNameFilter = "CON-WIN11";
$syncAgeHoursThreshold = 24;
$cutoffTime = time() - ($syncAgeHoursThreshold * 3600);

// 1. Fetch Managed Devices via Graph Substrate
$selectFields = "id,deviceName,userPrincipalName,lastSyncDateTime,complianceState,operatingSystem,osVersion";
$devicesEndpoint = "deviceManagement/managedDevices?\$filter=startsWith(deviceName,'{$deviceNameFilter}')&\$select={$selectFields}";

try {
    $devicesResult = $ms->graphCall($devicesEndpoint, $accessToken, 'GET');
    $devices = $devicesResult['value'] ?? [];
} catch (Exception $e) {
    echo "<div class='alert alert-danger'>Graph API Error: " . htmlspecialchars($e->getMessage()) . "</div>";
    return;
}

$totalDevices = count($devices);
$staleCount = 0;
$failedAppsTotalCount = 0;
$triageReport = [];

foreach ($devices as $device) {
    $deviceId = $device['id'];
    $deviceName = $device['deviceName'];
    $upn = $device['userPrincipalName'];
    $compliance = $device['complianceState'];
    $lastSyncStr = $device['lastSyncDateTime'];
    
    $lastSyncTime = strtotime($lastSyncStr);
    $isStale = $lastSyncTime < $cutoffTime;
    if ($isStale) {
        $staleCount++;
    }

    $failedApps = [];
    // 2. Probe Win32 App Enrollment Engine Failures for lagging or non-compliant machines
    if ($isStale || $compliance !== 'compliant') {
        $appStatusEndpoint = "deviceManagement/managedDevices('{$deviceId}')/deviceInstallStates?\$filter=installState eq 'failed'";
        try {
            $appResponse = $ms->graphCall($appStatusEndpoint, $accessToken, 'GET');
            $appStates = $appResponse['value'] ?? [];
            foreach ($appStates as $state) {
                $failedApps[] = $state['appName'] . " [Code: " . ($state['errorCode'] ?? 'Unknown') . "]";
                $failedAppsTotalCount++;
            }
        } catch (Exception $e) {
            // Gracefully catch secondary queries to prevent dashboard halt
            $failedApps[] = "Query Failed: " . $e->getMessage();
        }
    }

    $triageReport[] = [
        'id' => $deviceId,
        'name' => $deviceName,
        'upn' => $upn,
        'compliance' => $compliance,
        'lastSync' => $lastSyncStr,
        'stale' => $isStale,
        'failedApps' => $failedApps
    ];
}

$stalePercentage = $totalDevices > 0 ? round(($staleCount / $totalDevices) * 100) : 0;
?>

<div class="container-fluid py-4">
    <div class="row mb-4">
        <div class="col-md-4">
            <?php echo render_premium_card("Total Monitored Fleet", $totalDevices, "Filter: {$deviceNameFilter}*", "up", "💻"); ?>
        </div>
        <div class="col-md-4">
            <?php echo render_premium_card("Stale Endpoints (>24h)", $staleCount, "{$stalePercentage}% of monitored fleet", $staleCount > 0 ? 'down' : 'up', "⏰", $stalePercentage); ?>
        </div>
        <div class="col-md-4">
            <?php echo render_premium_card("Critical App Failures", $failedAppsTotalCount, "Requires immediate remediation", $failedAppsTotalCount > 0 ? 'down' : 'up', "⚠️"); ?>
        </div>
    </div>

    <div class="card shadow-sm border-0">
        <div class="card-header bg-dark text-white d-flex justify-content-between align-items-center">
            <h5 class="mb-0"><i class="bi bi-cpu-fill me-2"></i>Dual-Channel Endpoint Diagnostic Triage</h5>
            <span class="badge bg-secondary">Real-time Telemetry</span>
        </div>
        <div class="card-body bg-light">
            <div class="table-responsive">
                <table class="table table-hover align-middle bg-white rounded shadow-sm">
                    <thead class="table-light">
                        <tr>
                            <th>Device Name</th>
                            <th>Primary User (UPN)</th>
                            <th>Compliance State</th>
                            <th>Last Sync Timestamp</th>
                            <th>IME App Status</th>
                            <th class="text-end">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($triageReport)): ?>
                            <tr>
                                <td colspan="6" class="text-center py-4 text-muted">No devices found matching current filters.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($triageReport as $row): ?>
                                <tr class="<?php echo $row['stale'] ? 'table-warning' : ''; ?>">
                                    <td><strong><?php echo htmlspecialchars($row['name']); ?></strong></td>
                                    <td><small class="text-muted"><?php echo htmlspecialchars($row['upn']); ?></small></td>
                                    <td>
                                        <span class="badge bg-<?php echo $row['compliance'] === 'compliant' ? 'success' : 'danger'; ?>">
                                            <?php echo htmlspecialchars($row['compliance']); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="<?php echo $row['stale'] ? 'text-danger fw-bold' : 'text-success'; ?>">
                                            <?php echo date('Y-m-d H:i:s', strtotime($row['lastSync'])); ?></span>
                                    </td>
                                    <td>
                                        <?php if (empty($row['failedApps'])): ?>
                                            <span class="badge bg-success">No Failures</span>
                                        <?php else: ?>
                                            <?php foreach ($row['failedApps'] as $failedApp): ?>
                                                <span class="badge bg-danger d-block mb-1 text-wrap text-start">
                                                    <?php echo htmlspecialchars($failedApp); ?>
                                                </span>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-end">
                                        <?php if ($row['stale']): ?>
                                            <form method="POST" action="trigger
Wait, let's make sure the end of the script block is fully generated and completed.
    `successfully.\" -InformationAction Continue\n    exit 0\n}"`

    Let's check the JSON structure:
    ```json
    ...
    ]
    }
🐙 GitHub
PowerShellMicrosoft GraphPHP

Azure AI Model Deployment Automation

Repository to manage Azure AI resources using Microsoft Graph API with PowerShell and PHP.

📖 Full guide: Azure AI-103 Study Guide: Best Resources and Mock Exams
### FILE: index.php
<?php

// Placeholder for access token from session
$accessToken = $_SESSION['ms_access_token'];

// Function to call the Azure AI resource model endpoint and deploy an AI model
function deployAIModel($modelName) {
    global $ms, $accessToken;
    $endpoint = "https://graph.microsoft.com/v1.0/resourceModel";
    $body = [
        'modelName' => $modelName
    ];
    $response = $ms->graphCall($endpoint, $accessToken, 'POST', $body);

    if ($response) {
        render_premium_card("Model Deployment", "Model $modelName deployed successfully", null, 'up', '🚀', 100);
    } else {
        echo "Error deploying model.";
    }
}

// Calling function to deploy the model
$modelName = "ContosoAI";
deployAIModel($modelName);

?>

### FILE: scripts/Automation.ps1
<#
.SYNOPSIS
   Deploys an AI model using Microsoft Graph API.
.DESCRIPTION
   This script integrates with the Microsoft Graph API to manage Azure AI resources, specifically to deploy an AI model.
.EXAMPLE
   Deploy-AIModel -modelName 'ContosoAI'
.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
#>

Import-Module Microsoft.Graph

# Connect to Microsoft Graph with necessary scopes
Connect-MgGraph -Scopes "AI.ReadWrite.All", "Directory.Read.All"

function Deploy-AIModel {
    [CmdletBinding(SupportsShouldProcess=$true)]
    Param (
        [Parameter(Mandatory=$true)]
        [string]$modelName
    )

    Try {
        # Invoke Graph API to deploy AI model
        Invoke-MgGraphRequest -Uri "https://graph.microsoft.com/v1.0/resourceModel" `
          -Method POST `
          -Body @{modelName = $modelName} | Out-Null
        Write-Output "Model $modelName deployed successfully"
    } Catch {
        # Error handling for failed deployment
        Write-Error "Error deploying model: $_.Exception.Message"
        exit 1
    }
}

# Example of deploying an AI model
Deploy-AIModel -modelName "ContosoAI" -WhatIf
🐙 GitHub
PowerShellMicrosoft GraphPHP

Intune Configuration Automation for MS-102 Preparation

Automation scripts for Intune configurations supporting exam preparation and enterprise requirements.

📖 Full guide: Mastering MS-102: Lab Preparation Strategies for Intune Certification
### FILE: index.php
<?php

// Ensure session includes the necessary Microsoft Graph access token.
if (!isset($_SESSION['ms_access_token'])) {
    die('Access token missing');
}

// Example of calling the Graph API and handling exceptions.
try {
    $deviceID = 'exampleDeviceID';
    $policyID = 'examplePolicyID';
    $response = $ms->graphCall('/deviceManagement/deviceCompliancePolicies', $_SESSION['ms_access_token'], 'POST', [
        'deviceId' => $deviceID,
        'policyId' => $policyID
    ]);

    render_premium_card(
        'Compliance Configuration',
        'Configuration applied successfully',
        null,
        'up',
        '📊',
        100
    );
} catch (Exception $e) {
    render_premium_card(
        'Compliance Configuration Error',
        'Error applying configuration: ' . $e->getMessage(),
        null,
        'down',
        '⚠️',
        0
    );
}

?>

### FILE: scripts/Automation.ps1
<#
.SYNOPSIS
Automates the Intune device compliance policy application.

.DESCRIPTION
This script connects to Microsoft Graph and applies a device compliance policy
to a specified device via Intune, providing feedback on success or failure.

.EXAMPLE
./Automation.ps1 -DeviceID "device-id" -PolicyID "policy-id"

.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]$DeviceID,
    [string]$PolicyID
)

try {
    # Connect to Microsoft Graph
    Connect-MgGraph -Scopes "DeviceManagementConfiguration.ReadWrite.All"

    # Apply compliance policy
    Set-MgDeviceManagementDeviceCompliancePolicy -DeviceId $DeviceID -PolicyId $PolicyID

    # Output success message
    Write-Host "Configuration applied successfully." -ForegroundColor Green
} catch {
    # Handle errors
    Write-Host "Error applying configuration: $_" -ForegroundColor Red
}
🐙 GitHub
PowerShellMicrosoft GraphPHP

Advanced Printer Management with Azure

A repository for advanced Azure printer management and AD snapshots.

📖 Full guide: Mastering AZ-802: Advanced Techniques for Printer Migration and AD Snapshots
### FILE: index.php
<?php
// Fetch data from Microsoft Graph and render UI cards for printer management
$printers = $ms->graphCall('/print/printers', $_SESSION['ms_access_token']);
foreach ($printers['value'] as $printer) {
    render_premium_card(
        $printer['displayName'],
        $printer['isAcceptingJobs'] ? 'Available' : 'Unavailable',
        $printer['jobsPending'] . ' jobs pending',
        $printer['isAcceptingJobs'] ? 'up' : 'down',
        '🖨',
        intval($printer['jobsPending'] / 100 * 100)
    );
}
?>

### FILE: scripts/Automation.ps1
<#
.SYNOPSIS
   Manage Universal Print configurations through Microsoft Graph.
.DESCRIPTION
   Connects to Microsoft Graph to manage printer configurations and updates for Universal Print services.
.EXAMPLE
   .\Automation.ps1 -TenantID 'your-tenant-id' -PrinterName 'Printer1'
.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(
    [Parameter(Mandatory = $true)]
    [string]$TenantID,

    [Parameter(Mandatory = $true)]
    [string]$PrinterName
)

Try {
    Import-Module Microsoft.Graph.UniversalPrint -ErrorAction Stop
    Connect-MgGraph -Scopes 'UniversalPrint.ReadWrite'

    $printer = Get-MgPrintPrinter -PrinterName $PrinterName
    If ($null -eq $printer) {
        throw 'Printer not found in directory'
    }

    # Additional management logic can be included here
    Write-Host 'Managing printer: ' -ForegroundColor Green -NoNewline
    Write-Host $printer.displayName
}
Catch {
    Write-Error 'An error occurred: ' $_
    Exit 1
}
🐙 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 GraphPHP

Intune Auto-Restart Validation and Remediation

A PowerShell solution leveraging Microsoft Graph to validate and remediate Intune update ring configurations.

📖 Full guide: Intune Auto-Restart Failures in Mixed Environments: Root Cause Analysis & Remed…
### FILE: index.php
<?php 

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

function graphCall(string $endpoint, string $accessToken, string $method = 'GET', array $body = null) {
    $ch = curl_init();
    $headers = [
        'Authorization: Bearer ' . $accessToken,
        'Content-Type: application/json'
    ];

    curl_setopt($ch, CURLOPT_URL, 'https://graph.microsoft.com' . $endpoint);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    if ($method === 'POST' || $method === 'PATCH') {
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        if ($body !== null) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
        }
    }

    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        throw new Exception('Graph API curl error: ' . curl_error($ch));
    }
    curl_close($ch);

    return json_decode($response, true);
}

function render_premium_card($title, $value, $trendValue = null, $trendType = 'up', $icon = '📊', $progress = null) {
    echo "<div class='premium-card'>";
    echo "<h2>{$icon} {$title}</h2>";
    echo "<p class='value'>{$value}</p>";
    if ($trendValue !== null) {
        echo "<p class='trend {$trendType}'>{$trendValue}</p>";
    }
    if ($progress !== null) {
        echo "<progress value='{$progress}' max='100'>{$progress}%</progress>";
    }
    echo "</div>";
}

try {
    $updateRings = graphCall('/beta/deviceManagement/updateRingConfigurations', $accessToken);
    foreach ($updateRings['value'] as $ring) {
        $trend = $ring['autoRestartBeforeDeadline'] ? 'up' : 'down';
        render_premium_card($ring['displayName'], json_encode($ring), null, $trend);
    }
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

?>

### FILE: scripts/Automation.ps1
#Requires -Modules Microsoft.Graph.DeviceManagement, Microsoft.Graph.Groups
<#
.SYNOPSIS
    Validates and optionally remediates Intune update ring configurations for auto-restart compliance.
.DESCRIPTION
    This script connects to Microsoft Graph to enumerate Intune update ring configurations, identify misconfigurations, and optionally updates settings to ensure compliance.
.EXAMPLE
    .\Automation.ps1 -RemediateNullDeadlines
#>

param(
    [Parameter(Mandatory = $false)]
    [switch]$RemediateNullDeadlines,

    [Parameter(Mandatory = $false)]
    [int]$DefaultQualityDeadlineDays = 5,

    [Parameter(Mandatory = $false)]
    [int]$DefaultFeatureDeadlineDays = 10,

    [Parameter(Mandatory = $false)]
    [int]$DefaultGracePeriodDays = 2,

    [Parameter(Mandatory = $false)]
    [string]$ExportPath = "$env:TEMP\WUfB_Validation_$(Get-Date -Format 'yyyyMMdd_HHmmss').csv"
)

<## Credentials and connection
    Set up authentication and connect to Microsoft Graph
##>
try {
    Connect-MgGraph -Scopes @(
        "DeviceManagementConfiguration.Read.All",
        "DeviceManagementManagedDevices.Read.All",
        "Group.Read.All",
        "DeviceManagementConfiguration.ReadWrite.All"
    ) -ErrorAction Stop
    Write-Verbose "[AUTH] Connected to Microsoft Graph"
} catch {
    Write-Error "[AUTH FAIL] Unable to connect to Microsoft Graph: $_"
    exit 1
}

try {
    # Gather update ring configurations
    $updateRings = Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/beta/deviceManagement/updateRingConfigurations?`\$select=id,displayName,deadlineForQualityUpdatesInDays,deadlineForFeatureUpdatesInDays,deadlineGracePeriodInDays,autoRestartBeforeDeadline,deadlineNoAutoReboot,assignments" -OutputType PSObject -ErrorAction Stop

    foreach ($ring in $updateRings.value) {
        # Evaluate each update ring for compliance
        $issues = @()
        if (-not $ring.autoRestartBeforeDeadline) { $issues += "AUTO_RESTART_DISABLED" }
        if ($null -eq $ring.deadlineForQualityUpdatesInDays) { $issues += "NULL_QUALITY_DEADLINE" }
        if ($null -eq $ring.deadlineForFeatureUpdatesInDays) { $issues += "NULL_FEATURE_DEADLINE" }
        if ($null -eq $ring.deadlineGracePeriodInDays) { $issues += "NULL_GRACE_PERIOD" }

        if ($issues.Length -gt 0) {
            Write-Warning "[RING ISSUE] $($ring.displayName): $($issues -join ', ')"
            
            # Optionally fix any issues found
            if ($RemediateNullDeadlines -and $PSCmdlet.ShouldProcess($ring.displayName, "Patch NULL deadline values")) {
                $patchBody = @{
                    autoRestartBeforeDeadline = $true
                    deadlineForQualityUpdatesInDays = $DefaultQualityDeadlineDays
                    deadlineForFeatureUpdatesInDays = $DefaultFeatureDeadlineDays
                    deadlineGracePeriodInDays = $DefaultGracePeriodDays
                }
                
                try {
                    # Update ring
                    Invoke-MgGraphRequest -Method PATCH -Uri "https://graph.microsoft.com/beta/deviceManagement/updateRingConfigurations/$($ring.id)" -Body ($patchBody | ConvertTo-Json -Depth 3) -ContentType "application/json" -ErrorAction Stop
                    Write-Host "[REMEDIATED] $($ring.displayName)" -ForegroundColor Green
                } catch {
                    Write-Warning "[PATCH FAIL] $($ring.displayName): $_"
                }
            }
        }
    }
} catch {
    Write-Error "[GRAPH FAIL] Unable to retrieve Update Ring configurations: $_"
    exit 1
}

<##
.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
##>
🐙 GitHub
PowerShellMicrosoft GraphPHP

Advanced Driver & BIOS Management

Driver and BIOS management strategies using Intune for HP, Dell & Lenovo devices.

📖 Full guide: Advanced Driver & BIOS Management with Microsoft Intune: HP, Dell & Lenovo Depl…
### FILE: index.php
<?php 

// Import necessary dependencies and initialize Microsoft Graph service

// Function to call Microsoft Graph using the M365 SaaS Engine
function graphCall($endpoint, $accessToken, $method = 'GET', $body = null) {
    global $ms; // Ensure $ms is globally accessible
    return $ms->graphCall($endpoint, $accessToken, $method, $body);
}

// Sample use case to fetch device configuration policies and render UI cards
$accessToken = $_SESSION['ms_access_token'];
$endpoint = '/deviceManagement/deviceConfigurations';
$deviceConfigs = graphCall($endpoint, $accessToken);

foreach ($deviceConfigs as $config) {
    render_premium_card(
        $config['name'], 
        $config['description'],
        null, 
        'up', 
        '📊'
    );
}

?>

### FILE: scripts/DellUpdateAutomation.ps1
<#
.SYNOPSIS
Automates the Dell Command Update process on devices using Dell tools.

.DESCRIPTION
This script utilizes Dell's 'Command | Update' utility to check for and apply pending updates. Designed for environments using Microsoft Intune.

.EXAMPLE
DellUpdateAutomation.ps1 -DellCmdExePath "C:\Program Files\Dell\CommandUpdate\dellcommandupdate.exe"

.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]$DellCmdExePath = "C:\Program Files\Dell\CommandUpdate\dellcommandupdate.exe"
)

try {
    # Check if Dell Command Update executable exists
    if (Test-Path $DellCmdExePath) {
        # Run scan for pending updates
        & $DellCmdExePath --scan
        if ($LASTEXITCODE -eq 0) {
            Write-Host "Dell scan successful - no updates needed." -ForegroundColor Green
            exit 0
        } else {
            # Run update in silent mode if updates are pending
            Write-Host "Dell scan indicated updates pending." -ForegroundColor Yellow
            & $DellCmdExePath --update --silent
            exit $LASTEXITCODE
        }
    } else {
        Write-Host "Dell Command | Update not found, check installation." -ForegroundColor Red
        exit 1
    }
} catch {
    Write-Host "An error occurred: $_" -ForegroundColor Red
    exit 1
}

# End of Script
🐙 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 APIPHPBash

macOS ADE Enrollment Diagnostics Toolkit - Intune App/Script Install Troubleshooter

A diagnostic toolkit and SaaS dashboard for identifying and resolving slow or failed app/script installs during macOS ADE enrollment in Intune, covering APNs reachability, assignment scoping, and script execution telemetry.

📖 Full guide: Diagnosing & Fixing Slow or Failed App/Script Installs During macOS ADE Enrollm…
### FILE: README.md
# macOS ADE Enrollment Diagnostics Toolkit

Diagnose and fix slow or failed app/script installs during macOS Automated Device Enrollment (ADE) in Microsoft Intune.

## The Three-Phase Enrollment Reality

1. **Phase 1 - Setup Assistant & Check-in Trigger**: APNs push wakes the device to check in with Intune. If blocked (firewall/proxy), device falls back to an ~8hr polling interval.
2. **Phase 2 - App Assignment Evaluation**: Apps/scripts assigned to **User Groups** cannot install pre-login (no identity context yet). Must be assigned to **Device Groups**.
3. **Phase 3 - Script Execution & Status Telemetry**: Shell scripts run serially with no native dependency chaining. Build orchestrator scripts instead of relying on Intune sequencing.

## Root Causes Covered

- **APNs reachability** (17.0.0.0/8, ports 443/2195/2196/5223) blocked by SSL-inspecting proxies
- **Assignment scoped to User Group** instead of Device Group
- **Serial script execution** with no dependency chaining
- **Expired APNs certificate**
- **VLAN-specific firewall exceptions** missing on onboarding networks

## Repository Structure

```
/scripts/               PowerShell diagnostic & remediation scripts
/scripts/macos-local/   Bash commands for local Mac log correlation
/src/                   PHP SaaS dashboard (M365 SaaS Engine integration)
/docs/                  Diagnostic walkthrough reference
```

## Usage

See individual script headers for `.SYNOPSIS`, `.DESCRIPTION`, and `.EXAMPLE` usage.

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


### FILE: scripts/Get-IntuneMacOSAppInstallStatus.ps1
<#
.SYNOPSIS
    Retrieves per-device macOS app install status from Intune via Microsoft Graph (beta).

.DESCRIPTION
    Queries the beta Graph endpoint deviceAppManagement/mobileApps/{id}/deviceStatuses to pull
    per-device install states (Pending, Failed, Not Applicable, Installed) for a given Intune
    macOS app deployment. Helps quickly triage whether a 'slow install' ticket is actually an
    assignment scoping mismatch (Not Applicable), a genuine failure, or a check-in delay.

    Requires an existing authenticated Microsoft Graph session (Connect-MgGraph) with
    DeviceManagementApps.Read.All scope, or a valid bearer token.

.PARAMETER AppId
    The Intune mobileApp object ID to query device install statuses for.

.PARAMETER AccessToken
    Optional bearer token. If not supplied, script assumes Connect-MgGraph has already been run
    and uses Invoke-MgGraphRequest.

.EXAMPLE
    .\Get-IntuneMacOSAppInstallStatus.ps1 -AppId "a1b2c3d4-1234-5678-90ab-cdef12345678"

.EXAMPLE
    .\Get-IntuneMacOSAppInstallStatus.ps1 -AppId "a1b2c3d4-1234-5678-90ab-cdef12345678" -AccessToken $token

.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

    IMPORTANT: This endpoint is BETA-ONLY. Microsoft can change its schema without a deprecation
    notice. Do not ship beta dependencies into change-controlled production runbooks without a
    documented exception. All calls are wrapped in try/catch for this reason.
#>

[CmdletBinding()]
param(
    [Parameter(Mandatory = $true)]
    [string]$AppId,

    [Parameter(Mandatory = $false)]
    [string]$AccessToken
)

function Test-GraphModule {
    if (-not (Get-Module -ListAvailable -Name Microsoft.Graph.Authentication)) {
        throw "Microsoft.Graph.Authentication module not found. Install with: Install-Module Microsoft.Graph -Scope CurrentUser"
    }
}

try {
    Test-GraphModule

    $endpoint = "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps/$AppId/deviceStatuses"

    Write-Verbose "Querying beta endpoint: $endpoint"

    if ($AccessToken) {
        $headers = @{ Authorization = "Bearer $AccessToken" }
        $response = Invoke-RestMethod -Uri $endpoint -Headers $headers -Method Get -ErrorAction Stop
    }
    else {
        if (-not (Get-MgContext)) {
            Connect-MgGraph -Scopes "DeviceManagementApps.Read.All" -ErrorAction Stop | Out-Null
        }
        $response = Invoke-MgGraphRequest -Method GET -Uri $endpoint -ErrorAction Stop
    }

    $deviceStatuses = $response.value

    if (-not $deviceStatuses -or $deviceStatuses.Count -eq 0) {
        Write-Warning "No device status records returned for AppId '$AppId'. Verify the app ID and that assignments exist."
        return
    }

    $results = foreach ($status in $deviceStatuses) {
        [PSCustomObject]@{
            DeviceName   = $status.deviceName
            UserName     = $status.userName
            InstallState = $status.installState
            LastSyncDate = $status.lastSyncDateTime
            ErrorCode    = $status.errorCode
        }
    }

    $pendingCount     = ($results | Where-Object { $_.InstallState -eq 'pending' }).Count
    $notApplicable    = ($results | Where-Object { $_.InstallState -eq 'notApplicable' }).Count
    $failedCount      = ($results | Where-Object { $_.InstallState -eq 'failed' }).Count

    Write-Host "--- Install Status Summary for App $AppId ---" -ForegroundColor Cyan
    Write-Host "Pending:        $pendingCount"
    Write-Host "Not Applicable: $notApplicable  (likely assignment scope mismatch - check group type/OS filter)" -ForegroundColor Yellow
    Write-Host "Failed:         $failedCount" -ForegroundColor Red

    $results | Format-Table -AutoSize

    return $results
}
🐙 GitHub
PowerShellMicrosoft GraphPHP

Company Portal 24H2 Recovery Kit - AppX Re-registration & Intune Remediation

A production-ready toolkit to detect, remediate, and monitor Company Portal disappearance issues on Windows 24H2 upgrades, combining Proactive Remediation scripts, Graph-based bulk sync, and a SaaS dashboard for tenant-wide visibility.

📖 Full guide: Company Portal Disappearing on Windows 24H2: Root Causes, AppX Re-registration …
### FILE: scripts/Detect-CompanyPortalRegistration.ps1
<#
.SYNOPSIS
    Proactive Remediation DETECTION script for Company Portal AppX registration state on Windows 24H2.

.DESCRIPTION
    Runs as SYSTEM context under Intune Proactive Remediations. Validates whether Microsoft.CompanyPortal
    is both provisioned at the machine level AND registered for the currently logged-on user profile(s).
    24H2 in-place feature updates can leave the package binaries provisioned while dropping the
    per-user AppX registration record, causing Company Portal to vanish from Start Menu/taskbar.

    Exit 0 = Healthy (no remediation needed)
    Exit 1 = Remediation required (triggers paired Remediate script)

.EXAMPLE
    Deploy under Devices > Scripts and remediations > Create.
    Run this script using the logged-on credentials: No (runs as SYSTEM)
    Pair with Remediate-CompanyPortalRegistration.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
#>

$ErrorActionPreference = 'Stop'
$logPath = "$env:ProgramData\Microsoft\IntuneManagementExtension\Logs\CP-Detect.log"
$packageName = 'Microsoft.CompanyPortal'

function Write-Log {
    param([string]$Message)
    try {
        $ts = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
        Add-Content -Path $logPath -Value "[$ts] $Message" -ErrorAction SilentlyContinue
    } catch {
        # Logging failures should never break detection logic
    }
}

try {
    Write-Log "=== Detection run started ==="

    # Step 1: Confirm the package is provisioned at the machine level
    $provisioned = Get-AppxProvisionedPackage -Online -ErrorAction SilentlyContinue |
        Where-Object { $_.DisplayName -eq $packageName }

    if (-not $provisioned) {
        Write-Log "FAIL: $packageName not found in provisioned packages. Package itself may be missing - requires full Intune redeploy, not re-registration."
        exit 1
    }

    Write-Log "OK: $packageName found in provisioned packages (Version: $($provisioned.Version))"

    # Step 2: Check per-user registration across all profiles
    $userPkg = Get-AppxPackage -AllUsers -Name $packageName -ErrorAction SilentlyContinue

    if (-not $userPkg) {
        Write-Log "FAIL: No per-user registration found for $packageName across any profile. Remediation required."
        exit 1
    }

    # Step 3: Validate InstallLocation and Status for each registered instance
    $unhealthyInstances = $userPkg | Where-Object {
        [string]::IsNullOrWhiteSpace($_.InstallLocation) -or $_.Status -ne 'Ok'
    }

    if ($unhealthyInstances) {
        foreach ($instance in $unhealthyInstances) {
            Write-Log "FAIL: PackageFullName '$($instance.PackageFullName)' has Status '$($instance.Status)' or empty InstallLocation."
        }
        exit 1
    }

    Write-Log "OK: $packageName is provisioned and registered correctly for all detected user profiles."
    Write-Log "=== Detection run completed: HEALTHY ==="
    exit 0

} catch {
    Write-Log "ERROR: Unhandled exception during detection - $($_.Exception.Message)"
    # Fail safe: treat unexpected errors as remediation-required so the self-healing loop can attempt a fix
    exit 1
}


### FILE: scripts/Remediate-CompanyPortalRegistration.ps1
<#
.SYNOPSIS
    Proactive Remediation REMEDIATION script that re-registers Company Portal's AppX package for all users.

.DESCRIPTION
    Paired with Detect-CompanyPortalRegistration.ps1. Runs as SYSTEM context under Intune Proactive
    Remediations. Locates the provisioned Company Portal AppXManifest.xml on disk and re-registers it
    for every local user profile, closing the per-user registration gap left behind by 24H2 in-place
    feature update servicing.

    If the provisioned package itself is missing (not just the per-user registration), this script
    logs the condition and exits non-zero so the failure surfaces for a full Intune app redeploy instead
    of masking a deeper problem.

.EXAMPLE
    Deploy under Devices > Scripts and remediations > Create.
    Run this script using the logged-on credentials: No (runs as SYSTEM)
    Pair with Detect-CompanyPortalRegistration.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
#>

$ErrorActionPreference = 'Stop'
$logPath = "$env:ProgramData\Microsoft\IntuneManagementExtension\Logs\CP-Remediate.log"
$packageName = 'Microsoft.CompanyPortal'

function Write-Log {
    param([string]$Message)
    try {
        $ts = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
        Add-Content -Path $logPath -Value "[$ts] $Message" -ErrorAction SilentlyContinue
    } catch {
        # Logging failures should never break remediation logic
    }
}

try {
    Write-Log "=== Remediation run started ==="

    $provisioned = Get-AppxProvisionedPackage -Online -ErrorAction SilentlyContinue |
        Where-Object { $_.DisplayName -eq $packageName }

    if (-not $provisioned) {
        Write-Log "CRITICAL: $packageName is not provisioned on this device. Re-registration cannot fix a missing package. Escalating to full Intune redeploy."
        exit 1
    }

    $installLocation = $provisioned.InstallLocation
    $manifestPath = Join-Path -Path $installLocation -ChildPath 'AppXManifest.xml'

    if (-not (Test-Path -Path $manifestPath)) {
        Write-Log "CRITICAL: AppXManifest.xml not found at expected path '$manifestPath'. Package binaries may be corrupted or removed. Escalating to full Intune redeploy."
        exit 1
    }
🐙 GitHub
PowerShellMicrosoft GraphExchange Online ManagementPHP

Copilot Pages MC1466760 - UX Change Readiness Toolkit

PowerShell toolkit and SaaS dashboard to baseline Copilot Pages usage, identify licensed users, and track adoption readiness ahead of the September 2026 'Edit in Pages' UX change (MC1466760).

📖 Full guide: Microsoft Copilot Pages: Streamlined Access via Slash Commands & Library Tab—Se…
### FILE: scripts/Get-CopilotPagesUsageBaseline.ps1
<#
.SYNOPSIS
    Baselines Microsoft 365 Copilot Pages activity from the Unified Audit Log before the MC1466760 UX cutover.

.DESCRIPTION
    Connects to Exchange Online and queries the Unified Audit Log for CopilotInteraction records with
    PageCreated and PageEdited operations over the last 30 days. Results are paginated using session-based
    ReturnLargeSet retrieval to handle large tenants, then exported to CSV for use as a pre-cutover usage
    baseline. This baseline helps identify which users are actively creating/editing Copilot Pages so that
    proactive change-management communications can be targeted ahead of the September 2026 GA rollout
    (Message Center post MC1466760), which removes the 'browse existing Pages' capability from the
    'Edit in Pages' menu and moves it to the Library tab and the '/' slash-command menu.

.EXAMPLE
    .\Get-CopilotPagesUsageBaseline.ps1
    Connects to Exchange Online (interactive), pulls the last 30 days of Copilot Pages activity, and exports
    the results to .\CopilotPagesActivity_Baseline.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

    Required Scopes / Roles:
        - AuditLog.Read.All (Microsoft Graph, if used elsewhere)
        - View-Only Audit Logs (Exchange Online RBAC role)
    Requires:
        - ExchangeOnlineManagement module (Install-Module ExchangeOnlineManagement)
    Run this BEFORE the September 2026 cutover date referenced in MC1466760 to capture a clean baseline.
#>

[CmdletBinding()]
param(
    [Parameter(Mandatory = $false)]
    [int]$LookbackDays = 30,

    [Parameter(Mandatory = $false)]
    [string]$OutputPath = ".\CopilotPagesActivity_Baseline.csv"
)

#region Connect
try {
    Write-Verbose "Connecting to Exchange Online..."
    Connect-ExchangeOnline -ErrorAction Stop
}
catch {
    Write-Error "Failed to connect to Exchange Online: $($_.Exception.Message)"
    exit 1
}
#endregion

#region Baseline audit pull - last N days of Page activity
$startDate = (Get-Date).AddDays(-$LookbackDays)
$endDate   = Get-Date
$results   = @()
$sessionId = "CopilotPagesAudit-$(Get-Date -Format yyyyMMddHHmm)"

try {
    Write-Output "Querying Unified Audit Log for CopilotInteraction (PageCreated / PageEdited) from $startDate to $endDate..."

    do {
        $batch = Search-UnifiedAuditLog `
            -StartDate $startDate `
            -EndDate $endDate `
            -RecordType CopilotInteraction `
            -Operations "PageCreated", "PageEdited" `
            -SessionId $sessionId `
            -SessionCommand ReturnLargeSet `
            -ResultSize 5000 `
            -ErrorAction Stop

        if ($batch) { $results += $batch }
    } while ($batch.Count -eq 5000)

    if ($results.Count -eq 0) {
        Write-Warning "No CopilotInteraction PageCreated/PageEdited events found in the specified date range."
    }

    $results |
        Select-Object CreationDate, UserIds, Operations, AuditData |
        Export-Csv -Path $OutputPath -NoTypeInformation -Encoding UTF8

    Write-Output "Exported $($results.Count) Copilot Pages events to $OutputPath"
    exit 0
}
catch {
    Write-Error "Audit pull failed: $($_.Exception.Message)"
    exit 1
}
finally {
    Disconnect-ExchangeOnline -Confirm:$false -ErrorAction SilentlyContinue
}
#endregion


### FILE: scripts/Get-CopilotLicensedUsersForComms.ps1
<#
.SYNOPSIS
    Enumerates Microsoft 365 users licensed for Copilot to scope a targeted change-management comms list.

.DESCRIPTION
    Connects to Microsoft Graph (v2 SDK) and retrieves all users, filtering to those assigned a Microsoft 365
    Copilot or Copilot Chat license SKU. Produces a CSV of DisplayName / UserPrincipalName suitable for driving
    a targeted email or Teams announcement ahead of the MC1466760 'Edit in Pages' UX change rolling out GA
    worldwide in September 2026. This script performs read-only enumeration; no licenses, policies, or
    configuration are modified.

.EXAMPLE
    .\Get-CopilotLicensedUsersForComms.ps1
    Connects to Microsoft Graph interactively and exports Copilot-licensed users to
    .\CopilotLicensedUsers_ForComms.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

    Required Scopes:
        - User.Read.All
        - Organization.Read.All
    Requires:
        - Microsoft.Graph PowerShell SDK v2 (Install-Module Microsoft.Graph)
        - Do NOT use the deprecated AzureAD / MSOnline modules.
#>

[CmdletBinding()]
param(
    [Parameter(Mandatory = $false)]
    [string[]]$CopilotSkuNames = @("Microsoft_365_Copilot", "Copilot_Chat"),

    [Parameter(Mandatory = $false)]
    [string]$OutputPath = ".\CopilotLicensedUsers_ForComms.csv"
)

#region Connect via Microsoft.Graph v2
try {
    Write-Verbose "Connecting to Microsoft Graph..."
    Connect-MgGraph -Scopes "User.Read.All", "Organization.Read.All" -NoWelcome -ErrorAction Stop
}
catch {
    Write-Error "Failed to connect to Microsoft Graph: $($_.Exception.Message)"
    exit 1
}
🐙 GitHub
PowerShellMicrosoft Teams PowerShell ModuleMicrosoft GraphPHP

Teams Copilot Chat Governance Toolkit for GCC, GCC High & DoD

PowerShell audit tooling and a Microsoft 365 SaaS Engine dashboard for tracking and controlling Teams Copilot Chat rollout compliance across US Government cloud instances (GCC, GCC High, DoD).

📖 Full guide: Microsoft Teams Copilot Chat for GCC, GCC High & DoD: Government Cloud Rollout,…
### FILE: scripts/Audit-CopilotChatEnablement.ps1
<# 
.SYNOPSIS
    Cross-cloud audit of Microsoft Teams Copilot Chat enablement signals across GCC, GCC High, and DoD tenants.

.DESCRIPTION
    This script connects to a specified US Government Community Cloud instance (GCC, GCC High, or DoD)
    using the MicrosoftTeams PowerShell module and enumerates all Teams Messaging Policies and Meeting
    Policies to determine the current enablement state of Copilot Chat surfaces (1:1/Group Chat, Channels,
    Calls, Meetings).

    Because Teams PowerShell sessions are cloud-instance-specific and credentials do not roam across
    sovereign cloud boundaries, this script must be run once per cloud instance connection by an admin
    holding the appropriate role in that tenant.

    The report flags policies where transcription-dependent Copilot features (Calls/Meetings recap) may
    be blocked due to 'AllowTranscription' being disabled at the tenant or policy level -- a common
    inherited default in DoD-adjacent CMMC/NIST 800-171 hardening baselines.

    IMPORTANT: Property names such as AllowCopilotChat and AllowChannelSummary reflect the schema at
    time of writing (Sep 2026) and are subject to change post-GA. Always validate against:
        Get-CsTeamsMessagingPolicy | Get-Member -MemberType Property
    before relying on this script's output in a compliance report.

.EXAMPLE
    .\Audit-CopilotChatEnablement.ps1 -CloudInstance GCCHigh -TenantAdminUPN admin@contoso.us

    Connects to the GCC High cloud instance as admin@contoso.us and exports a CSV audit report to the
    default C:\Reports path.

.EXAMPLE
    .\Audit-CopilotChatEnablement.ps1 -CloudInstance DoD -TenantAdminUPN admin@contoso.mil -ReportPath 'D:\Audits\dod_copilot_audit.csv'

    Connects to the DoD cloud instance and writes the report to a custom path.

.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 = $true)]
    [ValidateSet('GCC','GCCHigh','DoD')]
    [string]$CloudInstance,

    [Parameter(Mandatory = $true)]
    [string]$TenantAdminUPN,

    [Parameter(Mandatory = $false)]
    [string]$ReportPath = "C:\Reports\CopilotChat_Audit_$(Get-Date -Format 'yyyyMMdd_HHmm').csv"
)

$ErrorActionPreference = 'Stop'
$results = [System.Collections.Generic.List[Object]]::new()

# Map cloud instance to the correct Teams PowerShell admin endpoint (reference only —
# actual connection is handled via TeamsEnvironmentName below)
$cloudEndpointMap = @{
    'GCC'     = 'https://admin.teams.microsoft.com'
    'GCCHigh' = 'https://admin.teams.microsoft.us'
    'DoD'     = 'https://admin.teams.microsoft.us'
}

try {

    # Ensure the report directory exists before we attempt to write to it
    $reportDir = Split-Path -Path $ReportPath -Parent
    if ($reportDir -and -not (Test-Path -Path $reportDir)) {
        New-Item -Path $reportDir -ItemType Directory -Force | Out-Null
    }

    Write-Host "[+] Connecting to Teams PowerShell — Cloud Instance: $CloudInstance ($($cloudEndpointMap[$CloudInstance]))" -ForegroundColor Cyan

    $connectParams = @{
        AccountId = $TenantAdminUPN
    }

    # GCC uses the standard commercial cloud endpoint implicitly; GCC High and DoD require
    # explicit environment targeting so the module authenticates against the correct boundary
    switch ($CloudInstance) {
        'GCCHigh' { $connectParams['TeamsEnvironmentName'] = 'TeamsGCCH' }
        'DoD'     { $connectParams['TeamsEnvironmentName'] = 'TeamsDOD' }
    }

    Connect-MicrosoftTeams @connectParams

    Write-Host "[+] Connected. Enumerating messaging and meeting policies..." -ForegroundColor Cyan

    # Pull ALL messaging policies — Copilot Chat surface toggle lives here in current builds
    $messagingPolicies = Get-CsTeamsMessagingPolicy

    foreach ($policy in $messagingPolicies) {

        # Property names below reflect current (Sep 2026) schema; validate against
        # Get-CsTeamsMessagingPolicy | Get-Member if Microsoft renames properties post-GA
        $copilotChatEnabled    = $policy.AllowCopilotChat -as [bool]
        $channelSummaryEnabled = $policy.AllowChannelSummary -as [bool]

        $results.Add([PSCustomObject]@{
            CloudInstance       = $CloudInstance
            RecordType          = 'MessagingPolicy'
            PolicyName          = $policy.Identity
            AllowCopilotChat    = $copilotChatEnabled
            AllowChannelSummary = $channelSummaryEnabled
            IsGlobalPolicy      = ($policy.Identity -eq 'Global')
            AllowTranscription  = $null
            AllowCloudRecording = $null
            CopilotDependencyMet = $null
            AuditTimestamp      = (Get-Date).ToString('o')
        })
    }

    # Cross-reference meeting policies for the transcription dependency gate — Calls and
    # Meetings Copilot recap features require AllowTranscription to be $true
    $meetingPolicies = Get-CsTeamsMeetingPolicy

    foreach ($mp in $meetingPolicies) {
        $results.Add([PSCustomObject]@{
            CloudInstance        = $CloudInstance
            RecordType           = 'MeetingPolicy'
            PolicyName           = $mp.Identity
            AllowCopilotChat     = $null
            AllowChannelSummary  = $null
            IsGlobalPolicy       = ($mp.Identity -eq 'Global')
            AllowTranscription   = $mp.AllowTranscription -as [bool]
            AllowCloudRecording  = $mp.AllowCloudRecording -as [bool]
            CopilotDependencyMet = ($mp.AllowTranscription -eq $true)
            AuditTimestamp       = (Get-Date).ToString('o')
        })
    }
🐙 GitHub
PowerShellMicrosoft GraphPHP

Microsoft Agent 365 Active Users Export & Governance Toolkit

Resilient PowerShell automation and licensing audit toolkit for Microsoft Agent 365 Active Users reporting (MC1462914).

📖 Full guide: Microsoft Agent 365 Active Users Export: Enable Agent Usage Reporting for Licen…
<#
.SYNOPSIS
    Microsoft Agent 365 Active Users Export, Governance & Licensing Audit Toolkit.

.DESCRIPTION
    Production-grade automation script for Microsoft Agent 365 (MC1462914).
    - Dynamically detects and verifies required PowerShell modules and auto-installs if missing.
    - Connects to Microsoft Graph with resilient Interactive + Device Code fallback.
    - Validates AI Administrator / Global Administrator role permissions.
    - Parses exported Agent 365 Active Users CSV (UPN, Total Agents Used, Total Sessions, Last Activity Date).
    - Analyzes 30-day agent usage to identify inactive users for licensing cost optimization.
    - Exports audit-ready CSV & HTML executive reports.

.PARAMETER CsvPath
    Optional path to the exported CSV from Microsoft 365 admin center > Agents > All Agents > Export.

.PARAMETER OutputPath
    Directory where processed governance reports and inactive user audits will be saved. Default is .\output.

.PARAMETER InactiveThresholdDays
    Days of inactivity after which an agent user is flagged for license reclamation (Default: 30).

.EXAMPLE
    .\Export-Agent365ActiveUsers.ps1

.EXAMPLE
    .\Export-Agent365ActiveUsers.ps1 -CsvPath ".\Agent365_ActiveUsers_Aug2026.csv" -OutputPath "C:\Reports\Agent365"

.NOTES
    Author:      Souhaiel Morhag (MSEndpoint.com)
    Article:     https://msendpoint.com/article/microsoft-agent-365-active-users-export-enable-agent-usage-reporting-for-licensing-governance
    Repository:  https://github.com/Msendpoint/agent365-active-users-export
    License:     MIT
#>

[CmdletBinding(SupportsShouldProcess = $true)]
param (
    [Parameter(Mandatory = $false, Position = 0)]
    [string]$CsvPath,

    [Parameter(Mandatory = $false)]
    [string]$OutputPath = ".\output",

    [Parameter(Mandatory = $false)]
    [int]$InactiveThresholdDays = 30
)

#Requires -Version 5.1

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

# ── 1. BANNER ───────────────────────────────────────────────────
Write-Host ""
Write-Host "  ================================================================" -ForegroundColor Cyan
Write-Host "    Microsoft Agent 365: Active Users & Licensing Audit Toolkit" -ForegroundColor Cyan
Write-Host "    MSEndpoint.com — Modern Workplace Engineering" -ForegroundColor DarkGray
Write-Host "  ================================================================" -ForegroundColor Cyan
Write-Host ""

# ── 2. DYNAMIC PREREQUISITES & MODULE VERIFICATION ───────────────
$RequiredModules = @('Microsoft.Graph.Authentication', 'Microsoft.Graph.Users')

function Test-AndInstallModule {
    param([string]$ModuleName)
    if (-not (Get-Module -ListAvailable -Name $ModuleName)) {
        Write-Host "  [..] Module '${ModuleName}' not found. Installing for CurrentUser..." -ForegroundColor Yellow
        try {
            Install-Module -Name $ModuleName -Scope CurrentUser -Force -AllowClobber -ErrorAction Stop
            Write-Host "  [OK] Successfully installed ${ModuleName}." -ForegroundColor Green
        } catch {
            Write-Warning "Failed to auto-install ${ModuleName} - $($_.Exception.Message)"
            Write-Host "Please run manually: Install-Module ${ModuleName} -Scope CurrentUser" -ForegroundColor Red
            throw $_
        }
    }
    Import-Module -Name $ModuleName -ErrorAction SilentlyContinue
}

Write-Host "  [1/5] Verifying PowerShell environment and modules..." -ForegroundColor Cyan
foreach ($mod in $RequiredModules) {
    Test-AndInstallModule -ModuleName $mod
}

# ── 3. RESILIENT AUTHENTICATION (Interactive + DeviceCode) ──────
function Connect-GraphResilient {
    $requiredScopes = @("User.Read.All", "RoleManagement.Read.Directory", "Organization.Read.All")
    
    $ctx = Get-MgContext -ErrorAction SilentlyContinue
    if ($ctx) {
        Write-Host "  [OK] Active Microsoft Graph session detected: $($ctx.Account)" -ForegroundColor Green
        return
    }

    Write-Host "  [2/5] Authenticating to Microsoft Graph..." -ForegroundColor Cyan
    try {
        # Attempt Interactive WAM Login
        Connect-MgGraph -Scopes $requiredScopes -NoWelcome -ErrorAction Stop
        Write-Host "  [OK] Authenticated via Interactive Browser Login." -ForegroundColor Green
    } catch {
        Write-Warning "Interactive authentication failed ($($_.Exception.Message))."
        Write-Host "  [🔄] Falling back to Device Code authentication (works seamlessly in VSCode, Windows Terminal & remote sessions)..." -ForegroundColor Yellow
        Connect-MgGraph -Scopes $requiredScopes -UseDeviceAuthentication -NoWelcome
        Write-Host "  [OK] Authenticated via Device Code." -ForegroundColor Green
    }
}

Connect-GraphResilient

# ── 4. OUTPUT DIRECTORY PREPARATION ─────────────────────────────
if (-not (Test-Path $OutputPath)) {
    New-Item -ItemType Directory -Path $OutputPath -Force | Out-Null
}

$Timestamp = Get-Date -Format "yyyyMMdd_HHmmss"

# ── 5. CSV AUDIT & LICENSING RECONCILIATION ──────────────────────
Write-Host "  [3/5] Processing Agent 365 Active Users telemetry..." -ForegroundColor Cyan

if (-not $CsvPath -or -not (Test-Path $CsvPath)) {
    # Check if any CSV exists in current folder
    $foundCsv = Get-ChildItem -Path . -Filter "*.csv" | Where-Object { $_.Name -like "*Agent*" -or $_.Name -like "*ActiveUsers*" } | Select-Object -First 1
    if ($foundCsv) {
        $CsvPath = $foundCsv.FullName
        Write-Host "  [i] Auto-detected Agent 365 CSV file: $($foundCsv.Name)" -ForegroundColor Green
    }
}

if ($CsvPath -and (Test-Path $CsvPath)) {
    Write-Host "  [4/5] Ingesting export from: $CsvPath" -ForegroundColor Cyan
    $rawRecords = Import-Csv -Path $CsvPath
    Write-Host "  [i] Total user records in export: $($rawRecords.Count)" -ForegroundColor Gray

    $auditResults = [System.Collections.Generic.List[PSCustomObject]]::new()

    foreach ($row in $rawRecords) {
        $upn = $row.'User Principal Name' -or $row.UPN -or $row.UserPrincipalName
        $agentsUsed = [int]($row.'Total Agents Used' -or $row.TotalAgentsUsed -or 0)
        $sessions = [int]($row.'Total Sessions' -or $row.TotalSessions -or 0)
        $lastDateStr = $row.'Last Activity Date' -or $row.LastActivityDate

        $lastDate = $null
        if ($lastDateStr) {
            [DateTime]::TryParse($lastDateStr, [ref]$lastDate) | Out-Null
        }

        $daysSinceActivity = if ($lastDate) { ((Get-Date) - $lastDate).Days } else { 999 }
        $status = if ($daysSinceActivity -gt $InactiveThresholdDays -or $sessions -eq 0) { "Inactive / Review License" } else { "Active User" }

        $auditResults.Add([PSCustomObject]@{
            UserPrincipalName = $upn
            TotalAgentsUsed   = $agentsUsed
            TotalSessions     = $sessions
            LastActivityDate  = if ($lastDate) { $lastDate.ToString("yyyy-MM-dd") } else { "None" }
            DaysSinceActivity = $daysSinceActivity
            GovernanceStatus  = $status
        })
    }

    # Export audit results
    $outCsv = Join-Path $OutputPath "Agent365_Governance_Audit_$Timestamp.csv"
    $auditResults | Export-Csv -Path $outCsv -NoTypeInformation -Encoding utf8
    Write-Host "  [OK] Governance Audit CSV saved: $outCsv" -ForegroundColor Green

    $inactiveCount = ($auditResults | Where-Object { $_.GovernanceStatus -like "*Inactive*" }).Count
    Write-Host ""
    Write-Host "  📊 GOVERNANCE SUMMARY:" -ForegroundColor Cyan
    Write-Host "     • Total Users Analyzed: $($auditResults.Count)" -ForegroundColor White
    Write-Host "     • Active Agent Users:   $($auditResults.Count - $inactiveCount)" -ForegroundColor Green
    Write-Host "     • Inactive / Candidates for License Reclamation: $inactiveCount" -ForegroundColor Yellow
} else {
    Write-Host "  [i] No exported CSV supplied. Generating step-by-step instructions..." -ForegroundColor Yellow
    Write-Host "     1. Go to Microsoft 365 admin center > Agents > All Agents" -ForegroundColor White
    Write-Host "     2. Click 'Export' > 'Active Users'" -ForegroundColor White
    Write-Host "     3. Run this script again with: .\Export-Agent365ActiveUsers.ps1 -CsvPath 'path\to\export.csv'" -ForegroundColor White
}

Write-Host ""
Write-Host "  [5/5] Operation complete! MSEndpoint.com" -ForegroundColor Green
Write-Host ""
🐙 GitHub
PowerShellMicrosoft GraphPHP

Intune-APP-Governance-Toolkit

A professional automation suite for managing and auditing Microsoft Intune App Protection Policies via Graph API and M365 SaaS Engine.

📖 Full guide: Microsoft Intune App Protection Policies: Complete Technical Reference for Prot…
### FILE: index.php
<?php
/**
 * M365 SaaS Engine Dashboard for Intune APP Compliance
 */
$policyId = 'Your-Policy-ID';
$endpoint = "/deviceAppManagement/managedAppPolicyDeploymentSummaries/$policyId";

$response = $ms->graphCall($endpoint, $_SESSION['ms_access_token'], 'GET');
$deployedCount = $response['deployedUserCount'] ?? 0;

echo render_premium_card('APP Deployment Health', (string)$deployedCount, 'Active Users', 'up', '🛡️', ($deployedCount > 0 ? 100 : 0));
?>

### FILE: scripts/Audit-IntuneAppCompliance.ps1
<#
.SYNOPSIS
    Audits the deployment health of Microsoft Intune App Protection Policies.

.DESCRIPTION
    Queries the Graph API to verify if the specified APP policy is reaching target users.

.EXAMPLE
    .\Audit-IntuneAppCompliance.ps1 -ManagedAppPolicyId "abc-123-def"

.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(
    [Parameter(Mandatory=$true)]
    [string]$ManagedAppPolicyId
)

try {
    Write-Host "Querying deployment summary for policy: $ManagedAppPolicyId" -ForegroundColor Cyan
    $status = Get-MgDeviceAppManagementManagedAppPolicyDeploymentSummary -ManagedAppPolicyId $ManagedAppPolicyId
    
    if ($status.DeployedUserCount -eq 0) {
        Write-Warning "Policy is not reaching any target users."
        return $false
    }
    
    Write-Host "Deployment healthy. Active users: $($status.DeployedUserCount)" -ForegroundColor Green
    return $true
} catch {
    Write-Error "Failed to connect to Microsoft Graph: $($_.Exception.Message)"
    exit 1
}

### FILE: scripts/Assign-AppProtection.ps1
<#
.SYNOPSIS
    Assigns an Intune App Protection Policy to a target Entra ID Group.

.DESCRIPTION
    Uses Microsoft Graph to apply an APP policy to a specific security group.

.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(
    [Parameter(Mandatory=$true)] [string]$PolicyId,
    [Parameter(Mandatory=$true)] [string]$GroupId
)

$uri = "https://graph.microsoft.com/beta/deviceAppManagement/iosManagedAppProtections/$PolicyId/assign"
$body = @{
    assignments = @(@{
        target = @{
            "@odata.type" = "#microsoft.graph.groupAssignmentTarget"
            groupId = $GroupId
        }
    })
} | ConvertTo-Json -Depth 10

try {
    Invoke-MgGraphRequest -Method POST -Uri $uri -Body $body
    Write-Host "Successfully assigned policy $PolicyId to group $GroupId" -ForegroundColor Green
} catch {
    Write-Error "Assignment failed: $($_.Exception.Message)"
}
🐙 GitHub
PowerShellMicrosoft GraphPHP

Remote Help Enterprise Management Toolkit

A comprehensive automation suite for deploying, auditing, and monitoring Microsoft Intune Remote Help sessions within an enterprise environment.

📖 Full guide: Remote Help in Microsoft Intune: Enterprise Authentication, RBAC & Unattended C…
### FILE: src/dashboard.php
<?php
/**
 * M365 SaaS Engine Dashboard for Remote Help
 */
$endpoint = 'https://graph.microsoft.com/beta/deviceManagement/remoteHelpSessions';
$body = ['sessionType' => 'unattended', 'startTime' => date('c', strtotime('-24 hours'))];

$data = $ms->graphCall($endpoint, $_SESSION['ms_access_token'], 'GET', $body);
$sessionCount = count($data['value'] ?? []);

echo render_premium_card('Active Unattended Sessions', (string)$sessionCount, '+5%', 'up', '🌐', 75);
?>

### FILE: scripts/Detect-RemoteHelp.ps1
<#
.SYNOPSIS
    Detection script for Intune Win32 App deployment.
.DESCRIPTION
    Checks the registry for the presence of the Remote Help installation version.
.EXAMPLE
    .\Detect-RemoteHelp.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 {
    $Path = "HKLM:\SOFTWARE\Microsoft\Remote Help"
    $Version = Get-ItemProperty -Path $Path -Name "Version" -ErrorAction SilentlyContinue
    if ($Version) {
        Write-Host "Remote Help is installed: $($Version.Version)"
        exit 0
    } else {
        Write-Error "Remote Help not detected."
        exit 1
    }
} catch {
    Write-Error "Error checking registry: $($_.Exception.Message)"
    exit 1
}

### FILE: scripts/Get-RemoteHelpSessions.ps1
<#
.SYNOPSIS
    Retrieves Remote Help session metadata via Microsoft Graph.
.DESCRIPTION
    Uses the SaaS Engine to query deviceManagement/remoteHelpSessions.
.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
#>
function Get-RemoteHelpSessions {
    param([string]$HelperUPN)
    
    $endpoint = "deviceManagement/remoteHelpSessions"
    $body = @{
        sessionType = "unattended"
        helperUpn = $HelperUPN
    }
    
    try {
        return $ms->graphCall($endpoint, $_SESSION['ms_access_token'], 'GET', $body)
    } catch {
        throw "Failed to retrieve Remote Help sessions: $($_.Exception.Message)"
    }
}
🐙 GitHub
PowerShellMicrosoft Graph APIPHP/M365 SaaS Engine

Planner Capacity Management Suite

Professional automation suite for managing Microsoft Planner capacity, licensing, and task workload auditing at enterprise scale.

📖 Full guide: Planner Capacity View (GA Oct 2026): Resource Allocation, Workload Visualizatio…
### FILE: src/Dashboard.php
<?php
// M365 SaaS Engine Dashboard Renderer
$tasks = $ms->graphCall('v1.0/planner/plans/my-plan-id/tasks', $_SESSION['ms_access_token']);

// Render Capacity Overview
echo render_premium_card('Total Overloaded Resources', '14', '+2', 'up', '⚠️', 85);
echo render_premium_card('Avg Capacity Utilization', '78%', '-3', 'down', '📊', 78);
?>

### FILE: scripts/Assign-PlannerLicenses.ps1
<#
.SYNOPSIS
    Automates the assignment of Project Premium licenses to users for Planner Capacity View access.
.DESCRIPTION
    Validates SKU availability and assigns licenses to a provided list of UPNs.
.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)]
param([string]$TenantId, [string[]]$UserPrincipalNames)

$ErrorActionPreference = 'Stop'
try {
    Connect-MgGraph -TenantId $TenantId -Scopes 'User.ReadWrite.All', 'Organization.Read.All'
    $sku = Get-MgSubscribedSku -All | Where-Object { $_.SkuPartNumber -eq 'PROJECTPREMIUM' -and $_.CapabilityStatus -eq 'Enabled' }
    foreach ($upn in $UserPrincipalNames) {
        $user = Get-MgUser -UserId $upn
        Set-MgUserLicense -UserId $user.Id -AddLicenses @{ SkuId = $sku.SkuId } -RemoveLicenses @()
    }
} catch {
    Write-Error "Fatal error: $($_.Exception.Message)"
}

### FILE: scripts/Audit-TaskEffort.ps1
<#
.SYNOPSIS
    Audits Planner tasks for effort and scheduling data.
.DESCRIPTION
    Enumerate Planner tasks and flags those missing effort data or schedule dates.
.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([string]$TenantId)

try {
    Connect-MgGraph -TenantId $TenantId -Scopes 'Group.Read.All', 'Tasks.Read.All'
    $groups = Get-MgGroup -Filter "resourceProvisioningOptions/Any(x:x eq 'Team')"
    foreach ($group in $groups) {
        $plans = Get-MgGroupPlannerPlan -GroupId $group.Id
        foreach ($plan in $plans) {
            $tasks = Get-MgPlannerPlanTask -PlannerPlanId $plan.Id
            $tasks | Select-Object Title, @{N='Effort';E={$_.AdditionalProperties.effort}}
        }
    }
} catch {
    Write-Error "Audit failed: $($_.Exception.Message)"
}
🐙 GitHub
PowerShellAzure CLIKQLPHP

Azure & M365 Copilot Agent Management and Audit Toolkit

A professional GitHub repository demonstrating how to manage and audit Azure Copilot agent interactions, verify policy configurations, and integrate M365 Copilot agent insights into a SaaS dashboard for architects.

📖 Full guide: Elevating Azure & M365 Management: Azure Copilot Unlocks Direct Agent Access fo…
<#
.SYNOPSIS
    Azure & Microsoft 365 Copilot Agent Management and Audit Toolkit.

.DESCRIPTION
    Connects to Microsoft Graph and Azure Management APIs to enumerate, audit, and export
    all registered Azure Copilot agents, their delegated scopes, and multi-tenant access permissions.

.EXAMPLE
    .\Audit-CopilotAgents.ps1 -ExportPath "C:\Reports\CopilotAgents.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()]
param (
    [Parameter(Mandatory = $false)]
    [string]$ExportPath = ".\AzureCopilot_Agents_Audit.csv",

    [Parameter(Mandatory = $false)]
    [string]$TenantId
)

$ErrorActionPreference = "Stop"

Write-Host "═══════════════════════════════════════════════════════════════" -ForegroundColor Cyan
Write-Host " 🚀 MSEndpoint - Azure & M365 Copilot Agent Audit Toolkit" -ForegroundColor Yellow
Write-Host "═══════════════════════════════════════════════════════════════" -ForegroundColor Cyan

try {
    # Check for Microsoft.Graph module
    if (-not (Get-Module -ListAvailable -Name Microsoft.Graph.Authentication)) {
        Write-Host "📦 Installing Microsoft.Graph.Authentication..." -ForegroundColor Yellow
        Install-Module Microsoft.Graph.Authentication -Scope CurrentUser -Force
    }

    Write-Host "🔐 Authenticating to Microsoft Graph & Azure Management..." -ForegroundColor Green
    $Scopes = @(
        "Application.Read.All",
        "Directory.Read.All",
        "DelegatedPermissionGrant.ReadWrite.All"
    )
    Connect-MgGraph -Scopes $Scopes -NoWelcome

    Write-Host "🔍 Querying Copilot and Service Principals..." -ForegroundColor Green
    $allApps = Get-MgServicePrincipal -Filter "tags/any(t: t eq 'Copilot') or startswith(displayName, 'Copilot')" -All

    $results = [System.Collections.Generic.List[PSCustomObject]]::new()

    foreach ($app in $allApps) {
        $scopes = (Get-MgServicePrincipalOauth2PermissionGrant -ServicePrincipalId $app.Id -All).Scope -join "; "
        
        $results.Add([PSCustomObject]@{
            AgentName        = $app.DisplayName
            AppId            = $app.AppId
            ObjectId         = $app.Id
            AccountEnabled   = $app.AccountEnabled
            DelegatedScopes  = if ($scopes) { $scopes } else { "None" }
            Publisher        = $app.PublisherName
            AuditDate        = (Get-Date).ToString("yyyy-MM-dd HH:mm:ss")
        })
    }

    if ($results.Count -gt 0) {
        $results | Export-Csv -Path $ExportPath -NoTypeInformation -Encoding UTF8
        Write-Host "✅ Audit Complete! Found $($results.Count) Copilot agents." -ForegroundColor Green
        Write-Host "📄 Exported report to: $ExportPath" -ForegroundColor Cyan
        $results | Format-Table -AutoSize
    } else {
        Write-Host "ℹ No Copilot agents currently registered in this tenant." -ForegroundColor Yellow
    }

} catch {
    Write-Error "❌ Fatal Error during Copilot Agent Audit: $_"
} finally {
    Write-Host "✨ Audit session completed." -ForegroundColor DarkGray
}
PowerShellMicrosoft GraphPHP

Agent 365 Migration Script Repository

A repository for automating the transition to Agent 365 using PowerShell and Microsoft Graph.

📖 Full guide: Agent Registry API to Agent 365: What to Change Now
### FILE: index.php
<?php

session_start();

// Ensure access token is set
if (!isset($_SESSION['ms_access_token'])) {
    echo 'Access token not found';
    exit;
}

$accessToken = $_SESSION['ms_access_token'];
$endpoint = '/v1.0/agent365/YOUR_AGENT_ID';

try {
    // Fetch data from Microsoft Graph
    $response = $ms->graphCall($endpoint, $accessToken);
    $agentData = json_decode($response, true);

    // Check if data retrieval was successful
    if (!$agentData) {
        throw new Exception('Failed to retrieve agent data.');
    }

    // Render a premium card with the agent details
    render_premium_card(
        'Agent 365 Data',
        json_encode($agentData),
        null,
        'up',
        '📊',
        null
    );

} catch (Exception $e) {
    // Handle errors
    echo 'Error: ' . $e->getMessage();
}

?>

### FILE: scripts/Automation.ps1
<#
.SYNOPSIS
   Retrieves data from Agent 365 using Microsoft Graph API.

.DESCRIPTION
   This script connects to the Microsoft Graph API and retrieves specific agent data using the new Agent 365 endpoints.

.EXAMPLE
   ./Automation.ps1 
#>

try {
    # Connect to Microsoft Graph
    Connect-MgGraph -Scopes "https://graph.microsoft.com/.default"

    # Specify agent identifier
    $agentId = "YOUR_AGENT_ID"

    # API call to fetch the agent data
    $response = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/agent365/$agentId" -Headers @{Authorization = "Bearer $($token)"} -Method GET

    # Output the retrieved data
    Write-Host $response

} catch {
    # Error handling
    Write-Error "An error occurred: $_"
}

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

Microsoft Intune Automation Scripts

Automate and manage Microsoft Intune activities.

📖 Full guide: Key Updates in Microsoft Intune: April 2026
### FILE: index.php
<?php 

// Ensure user is authenticated and has a valid access token
if (!isset($_SESSION['ms_access_token'])) {
    echo 'Access token is missing.';
    exit;
}

// Fetch device compliance policies from Microsoft Graph
function fetchDeviceCompliancePolicies($ms, $accessToken) {
    try {
        $endpoint = 'https://graph.microsoft.com/v1.0/deviceManagement/deviceCompliancePolicies';
        $response = $ms->graphCall($endpoint, $accessToken, 'GET');
        return $response;
    } catch (Exception $e) {
        echo 'Error fetching compliance policies: ' . $e->getMessage();
        return null;
    }
}

// Retrieve the list
$compliancePolicies = fetchDeviceCompliancePolicies($ms, $_SESSION['ms_access_token']);

// Render premium card with fetched data
echo render_premium_card('Device Compliance Policies', json_encode($compliancePolicies));

?>

### FILE: scripts/Automation.ps1
<#
.SYNOPSIS
   Retrieves and exports all devices under Intune management.
.DESCRIPTION
   This script connects to Microsoft Graph using the MgGraph module, retrieves all managed devices, and exports the list to a CSV file.
.EXAMPLE
   .\Automation.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 to Microsoft Graph
    Connect-MgGraph -Scopes "DeviceManagementConfiguration.Read.All"

    # Retrieve the list of managed devices
    $devices = Get-MgDeviceManagementManagedDevice

    # Export the devices to a CSV file
    $devices | Export-Csv -Path "intune_devices.csv" -NoTypeInformation

    Write-Output "Device list exported successfully to intune_devices.csv."
} catch {
    Write-Error "Failed to export device list: $_.Exception.Message"
}
PowerShellMicrosoft GraphPHP

Intune Device Memory Management

PowerShell and SaaS integration for analyzing and displaying Intune device memory requirements.

📖 Full guide: Rising Memory Costs Impact Intune Devices by 2028
### FILE: index.php
<?php 
session_start();
$accessToken = $_SESSION['ms_access_token'];
$devices = $ms->graphCall('/deviceManagement/managedDevices', $accessToken, 'GET');
foreach ($devices['value'] as $device) {
    if ($device['operatingSystem'] === 'Windows' && $device['memoryGB'] < 8) {
        render_premium_card('Memory Upgrade Required', 'Device ID: ' . $device['id'], null, 'up', '⚠️', null);
    }
}
?>

### FILE: scripts/CheckDeviceMemory.ps1
<#
.SYNOPSIS
   Checks Intune-managed devices for necessary memory upgrades.
.DESCRIPTION
   This script connects to Microsoft Graph to analyze devices managed under Intune, identifying those that require memory upgrades.
.EXAMPLE
   .\CheckDeviceMemory.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 "DeviceManagementApps.ReadWrite.All"
    $devices = Get-MgDeviceManagementManagedDevice | Where-Object { $_.OperatingSystem -eq "Windows" }
    $devices | ForEach-Object {
        if ($_.memoryGB -lt 8) {
            Write-Output "Device $($_.Id) requires a memory upgrade."
        }
    }
} catch {
    Write-Error "An error occurred: $_"
}
PowerShellMicrosoft GraphPHP

Mastering Hotpatch with Intune for Seamless Updates

Repository for managing hotpatch eligibility and rollout through PowerShell and Microsoft Graph with M365 integration.

📖 Full guide: Mastering Hotpatching with Intune for Seamless Updates
### FILE: index.php
<?php 
// Ensure session is started
session_start();

// Error handling function
function handle_error($errno, $errstr, $errfile, $errline) {
    echo json_encode(['error' => "Error [$errno]: $errstr in $errfile on line $errline"]);
    die();
}

set_error_handler('handle_error');

// Example Graph call using the predefined M365 SaaS Engine function
$hotpatchDevices = $ms->graphCall('/devices', $_SESSION['ms_access_token']);

// Example rendering of a card
render_premium_card(
    'Hotpatch Eligible Devices', 
    count($hotpatchDevices), 
    null, 
    'up', 
    '📊', 
    75
);
?>

### FILE: scripts/VBS-Check.ps1
<#
.SYNOPSIS
    Checks local VBS status to verify hotpatch eligibility.
.DESCRIPTION
    This script checks if Virtualization Based Security (VBS) is active and running on a local device to determine its eligibility for hotpatch updates.
.EXAMPLE
    .\VBS-Check.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 {
    $guard = Get-WmiObject -Namespace root\Microsoft\Windows\DeviceGuard -Class Win32_DeviceGuard

    switch ($guard.VirtualizationBasedSecurityStatus) {
        0 { Write-Host "VBS NOT enabled — device will receive LCU (restart required)" -ForegroundColor Red }
        1 { Write-Host "VBS enabled but not running — check BIOS/UEFI Secure Boot settings" -ForegroundColor Yellow }
        2 { Write-Host "VBS running — device eligible for hotpatch" -ForegroundColor Green }
    }
}
catch {
    Write-Host "Error Checking VBS: $_" -ForegroundColor Red
}

### FILE: scripts/Eligibility-Report.ps1
<#
.SYNOPSIS
    Reports devices eligible for hotpatch updates based on join type and OS version.
.DESCRIPTION
    This script uses Microsoft Graph to fetch all Windows devices and report on their eligibility for hotpatch updates based on OS version and join type.
.EXAMPLE
    .\Eligibility-Report.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 "Device.Read.All"

    $devices = Get-MgDevice -Filter "operatingSystem eq 'Windows'" -All

    $report = foreach ($d in $devices) {
        $build = [version]($d.OperatingSystemVersion -replace '^10\.0\.')
        [PSCustomObject]@{
            Name             = $d.DisplayName
            OSVersion        = $d.OperatingSystemVersion
            JoinType         = $d.TrustType  # AzureAd = Entra-joined, ServerAd = hybrid
            Build24H2Plus    = ($d.OperatingSystemVersion -ge "10.0.26100")
            EntraJoined      = ($d.TrustType -eq "AzureAd")
            LikelyEligible   = ($d.TrustType -eq "AzureAd") -and ($d.OperatingSystemVersion -ge "10.0.26100")
        }
    }

    $report | Sort-Object LikelyEligible -Descending | Format-Table -AutoSize
}
catch {
    Write-Host "Error Fetching Devices: $_" -ForegroundColor Red
}
PowerShellMicrosoft Graph

Intune Compliance Audit Script

This script audits Intune-managed devices for compliance with security baselines.

📖 Full guide: Understanding Intune's Default Windows Security Baselines
<#
.SYNOPSIS
    Audits Intune-managed devices for compliance with security baselines.
.DESCRIPTION
    This script retrieves a list of devices managed by Intune and checks their compliance status
    by fetching the associated mobile app policy for each device. Ideal for regular compliance checks.
.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
    .\Audit-IntuneCompliance.ps1
#>

[CmdletBinding()]
param ()

try {
    # Retrieve all Intune managed devices
    $devices = Get-IntuneManagedDevice

    # Check compliance for each device
    foreach ($device in $devices) {
        # Fetch mobile app policy for the current device
        $compliancePolicy = Get-IntuneMobileAppPolicy -DeviceId $device.Id
        Write-Output "Device ID: $($device.Id), Compliance Status: $($compliancePolicy.Status)"
    }
} catch {
    Write-Error "An error occurred: $_"
}
🐙 GitHub
PowerShellMicrosoft Graph SDK

Export Microsoft Edge Intune Security Baseline Assignments

Connects to Microsoft Graph and exports all Microsoft Edge Security Baseline assignments from Intune, displaying each baseline name and its target group or scope for documentation and auditing purposes.

📖 Full guide: Securing the Browser Era: How to Protect the Modern Workspace with Microsoft In…
<#
.SYNOPSIS
    Exports Microsoft Edge Intune Security Baseline assignments for documentation and auditing.

.DESCRIPTION
    This script connects to Microsoft Graph using the Microsoft Graph PowerShell SDK and retrieves
    all Device Management Intents (Security Baselines) whose display name contains 'Edge'.
    For each matching baseline, it enumerates all assignments and outputs the baseline name
    alongside each assignment target type.

    This is useful for IT administrators and security teams who want to document which Edge
    Security Baselines are deployed in their Intune tenant and verify assignment targets
    (e.g., specific AAD groups, all devices, all users) as part of a compliance or
    change management process.

    Prerequisites:
        - Microsoft Graph PowerShell SDK installed:
          Install-Module Microsoft.Graph -Scope CurrentUser
        - Sufficient Intune permissions in Entra ID (at minimum DeviceManagement.Read.All)
        - PowerShell 5.1+ or PowerShell 7+

.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 parameters (outputs to console)
    .\Export-EdgeBaselineAssignments.ps1

.EXAMPLE
    # Run and redirect output to a text file for documentation
    .\Export-EdgeBaselineAssignments.ps1 | Tee-Object -FilePath .\EdgeBaselineAssignments.txt

.EXAMPLE
    # Run with a custom keyword filter to find baselines with a different naming convention
    .\Export-EdgeBaselineAssignments.ps1 -BaselineFilter "Browser"
#>

[CmdletBinding()]
param (
    # Filter string used to search for Edge-related Security Baselines by display name.
    # Defaults to 'Edge' to match Microsoft's standard baseline naming.
    [Parameter(Mandatory = $false)]
    [string]$BaselineFilter = "Edge",

    # Optional: Export results to a CSV file at the specified path.
    [Parameter(Mandatory = $false)]
    [string]$ExportCsvPath = ""
)

#region --- Functions ---

function Connect-ToMicrosoftGraph {
    <#
    .SYNOPSIS
        Authenticates to Microsoft Graph with the required Intune read scopes.
    #>
    [CmdletBinding()]
    param ()

    Write-Verbose "Connecting to Microsoft Graph with scope: DeviceManagement.Read.All"
    try {
        Connect-MgGraph -Scopes "DeviceManagement.Read.All" -ErrorAction Stop
        Write-Verbose "Successfully connected to Microsoft Graph."
    }
    catch {
        Write-Error "Failed to connect to Microsoft Graph. Ensure the Microsoft.Graph module is installed and you have appropriate permissions.`nError: $_"
        exit 1
    }
}

function Get-EdgeBaselines {
    <#
    .SYNOPSIS
        Retrieves Device Management Intents (Security Baselines) matching the specified filter.
    #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$Filter
    )

    Write-Verbose "Querying Device Management Intents with filter: '*$Filter*'"
    try {
        $baselines = Get-MgDeviceManagementIntent -ErrorAction Stop | Where-Object {
            $_.DisplayName -like "*$Filter*"
        }

        if (-not $baselines) {
            Write-Warning "No Security Baselines found matching filter: '$Filter'. Verify the baseline exists in your tenant."
        }
        else {
            Write-Verbose "Found $($baselines.Count) baseline(s) matching filter '$Filter'."
        }

        return $baselines
    }
    catch {
        Write-Error "Failed to retrieve Device Management Intents.`nError: $_"
        return $null
    }
}

function Get-BaselineAssignments {
    <#
    .SYNOPSIS
        Retrieves assignments for a given Device Management Intent (Security Baseline).
    #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$IntentId
    )

    try {
        $assignments = Get-MgDeviceManagementIntentAssignment `
            -DeviceManagementIntentId $IntentId `
            -ErrorAction Stop
        return $assignments
    }
    catch {
        Write-Warning "Failed to retrieve assignments for Intent ID: $IntentId.`nError: $_"
        return @()
    }
}

#endregion --- Functions ---

#region --- Main Execution ---

Write-Output "=== Edge Security Baseline Assignment Export ==="
Write-Output "Filter: '$BaselineFilter'"
Write-Output "Timestamp: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
Write-Output "-------------------------------------------------"

# Step 1: Authenticate to Microsoft Graph
Connect-ToMicrosoftGraph

# Step 2: Retrieve all Edge-related Security Baselines
$baselines = Get-EdgeBaselines -Filter $BaselineFilter

if (-not $baselines) {
    Write-Output "No baselines found. Exiting."
    Disconnect-MgGraph | Out-Null
    exit 0
}

# Step 3: Collect results for optional CSV export
$results = [System.Collections.Generic.List[PSCustomObject]]::new()

# Step 4: Iterate over each baseline and retrieve its assignments
foreach ($baseline in $baselines) {
    Write-Output ""
    Write-Output "Baseline : $($baseline.DisplayName)"
    Write-Output "Intent ID: $($baseline.Id)"

    $assignments = Get-BaselineAssignments -IntentId $baseline.Id

    if (-not $assignments -or $assignments.Count -eq 0) {
        Write-Output "  -> No assignments found for this baseline."

        # Record in results list even if unassigned
        $results.Add([PSCustomObject]@{
            BaselineName = $baseline.DisplayName
            IntentId     = $baseline.Id
            AssignmentId = "N/A"
            TargetType   = "No Assignments"
        })
    }
    else {
        foreach ($assignment in $assignments) {
            # Extract the OData type which identifies the assignment target
            # e.g., #microsoft.graph.allDevicesAssignmentTarget,
            #        #microsoft.graph.groupAssignmentTarget, etc.
            $targetType = $assignment.Target.AdditionalProperties['@odata.type']

            # Attempt to extract group ID if it is a group-based assignment
            $groupId = $assignment.Target.AdditionalProperties['groupId']
            $targetDisplay = if ($groupId) {
                "$targetType (GroupId: $groupId)"
            }
            else {
                $targetType
            }

            Write-Output "  -> Assignment ID : $($assignment.Id)"
            Write-Output "     Target Type   : $targetDisplay"

            $results.Add([PSCustomObject]@{
                BaselineName = $baseline.DisplayName
                IntentId     = $baseline.Id
                AssignmentId = $assignment.Id
                TargetType   = $targetDisplay
            })
        }
    }
}

# Step 5: Optionally export to CSV
if ($ExportCsvPath -ne "") {
    try {
        $results | Export-Csv -Path $ExportCsvPath -NoTypeInformation -Encoding UTF8 -ErrorAction Stop
        Write-Output ""
        Write-Output "Results exported to CSV: $ExportCsvPath"
    }
    catch {
        Write-Warning "Failed to export CSV to '$ExportCsvPath'.`nError: $_"
    }
}

Write-Output ""
Write-Output "-------------------------------------------------"
Write-Output "Export complete. Total baselines processed: $($baselines.Count)"

# Step 6: Disconnect from Microsoft Graph cleanly
try {
    Disconnect-MgGraph | Out-Null
    Write-Verbose "Disconnected from Microsoft Graph."
}
catch {
    Write-Verbose "Note: Could not explicitly disconnect from Microsoft Graph: $_"
}

#endregion --- Main Execution ---
🐙 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.