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

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

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

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

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 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 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
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"
}
PowerShell

Automate Enrollment of Apple TV Devices

Automate the enrollment of corporate-owned Apple TV devices into Microsoft Intune using Apple's ADE.

📖 Full guide: Automate Apple TV Enrollment with ADE in Intune
[{"path":"index.php","content":"<?php\n\n\/* Logic to authenticate against Microsoft Graph and enroll Apple TV devices using M365 SaaS Engine. \n*\/\n\nsession_start();\n\n\/\/ Authenticate and get access token\n$accessToken = $_SESSION['ms_access_token'];\n\n\/\/ Enroll Apple TV Devices function\nfunction enrollAppleTvDevices($appleTeamID, $intuneProfileID) {\n    global $ms, $accessToken;\n\n    \/\/ Graph API endpoint to enroll devices\n    $endpoint = \"https:\/\/graph.microsoft.com\/v1.0\/deviceManagement\/appleEnrollmentProfiles\/$intuneProfileID\/devices\/$appleTeamID\/enroll\";\n    \n    \/\/ Make the graph call and check the result\n    $result = $ms->graphCall($endpoint, $accessToken, 'POST');\n\n    if ($result) {\n        render_premium_card('Enrollment Success', 'Successfully enrolled devices', null, 'up', '📊', 100);\n    } else {\n        render_premium_card('Enrollment Failed', 'Failed to enroll devices', null, 'down', '⚠️', 0);\n    }\n}\n\n\/\/ Example of enrolling devices\n$appleTeamID = '12345678'; \/\/ Example placeholder value\n$intuneProfileID = 'abc-123'; \/\/ Example placeholder value\nenrollAppleTvDevices($appleTeamID, $intuneProfileID);\n\n?>"},{"path":"scripts\/Automation.ps1","content":"<#\n.SYNOPSIS\nAutomates the enrollment of Apple TV devices into Microsoft Intune.\n.DESCRIPTION\nThis PowerShell script uses Microsoft Graph API to enroll corporate-owned Apple TV devices into Intune leveraging Apple's Automated Device Enrollment.\nThe script supports bulk enrollments by sending a POST request to the Intune API with the necessary identifiers.\n.EXAMPLE\n.\/EnrollAppleTVDevices.ps1 -AppleTeamID \"12345678\" -IntuneProfileID \"abc-123\"\n.NOTES\nAuthor:      Souhaiel Morhag\nCompany:     MSEndpoint.com\nBlog:        https:\/\/msendpoint.com\nAcademy:     https:\/\/app.msendpoint.com\/academy\nLinkedIn:    https:\/\/linkedin.com\/in\/souhaiel-morhag\nGitHub:      https:\/\/github.com\/Msendpoint\nLicense:     MIT\n#>\n\n[CmdletBinding()]\nParam(\n    [Parameter(Mandatory=$true, Position=0)]\n    [string]$AppleTeamID = \"YOUR_VALUE\",\n\n    [Parameter(Mandatory=$true, Position=1)]\n    [string]$IntuneProfileID = \"YOUR_VALUE\"\n)\n\ntry {\n    # Connects to Microsoft Graph with the required permissions\n    Connect-MgGraph -Scopes \"DeviceManagementManagedDevices.ReadWrite.All\"\n    \n    # Enroll Apple devices using the Graph API endpoint\n    $result = Invoke-RestMethod -Uri \"https:\/\/graph.microsoft.com\/v1.0\/deviceManagement\/appleEnrollmentProfiles\/$IntuneProfileID\/devices\/$AppleTeamID\/enroll\" -Method Post\n\n    # Output result upon successful enrollment\n    Write-Output \"Successfully enrolled devices under Apple Team ID: $AppleTeamID\"\n}\ncatch {\n    Write-Error \"Failed to enroll devices: $_\"\n}\nfinally {\n    if (-not $result) {\n        Write-Output \"No result returned from the Graph API call.\"\n    }\n}\n"}]
🐙 GitHub
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 Intune Proactive RemediationWindows Registry

Outlook Hyperlink Warning Remediation and Trusted Sites Configuration via Intune

Detects and remediates Outlook and Office hyperlink security warnings while configuring trusted sites in the Internet Zone registry via Intune Proactive Remediation scripts.

📖 Full guide: Remove Outlook Security Warnings & Configure Trusted Sites via Intune Policy
<#
.SYNOPSIS
    Detects and remediates Outlook hyperlink security warnings and configures trusted sites via registry settings.

.DESCRIPTION
    This script is designed to be deployed as an Intune Proactive Remediation package (Detection + Remediation).
    It targets two common pain points in enterprise environments:
      1. Microsoft Outlook and Office applications displaying intrusive security warnings when users
         click on hyperlinks pointing to trusted internal resources (file servers, SharePoint, etc.).
      2. Missing or incorrect ZoneMap registry entries that define trusted sites for Internet Explorer
         and legacy Office security zones.

    The DETECTION script checks:
      - Whether each trusted site is registered in the ZoneMap registry key under HKLM Policies.
      - Whether the 'DisableHyperlinkWarning' DWORD is set to 1 in both the Outlook and Office
        security registry paths.
    Exits 0 (Compliant) or 1 (Non-Compliant) so Intune can trigger remediation accordingly.

    The REMEDIATION script:
      - Creates the ZoneMap registry path if missing and adds/updates all trusted site entries.
      - Creates the Outlook and Office security registry paths if missing.
      - Sets 'DisableHyperlinkWarning' to 1 in both paths to suppress security prompts.

    HOW TO DEPLOY:
      1. Save the Detection block and Remediation block as separate .ps1 files.
      2. In the Intune Admin Center, navigate to:
         Devices > Manage devices > Scripts and remediations > Create script package.
      3. Upload the Detection script and Remediation script, assign to target device groups.
      4. Monitor results under Devices > Manage devices > Scripts and remediations.

    CUSTOMIZATION:
      Update the $trustedSites hashtable in both scripts to reflect your organization's internal
      hostnames, file server UNC paths, and SharePoint URLs before deployment.

.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 the detection script manually to check compliance on a local machine:
    .\Detect-OutlookHyperlinkWarning.ps1

    # Run the remediation script manually to apply registry changes:
    .\Remediate-OutlookHyperlinkWarning.ps1
#>

[CmdletBinding()]
param (
    # Set to 'Detect' to run detection logic only, or 'Remediate' to apply fixes.
    [ValidateSet('Detect', 'Remediate')]
    [string]$Mode = 'Detect'
)

#region --- Configuration ---

# Registry path for ZoneMap trusted sites (Machine-level, enforced via policy)
$zoneMapPath = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains'

# Registry path for Outlook 2016/365 security settings (per-user)
$outlookSecurityPath = 'HKCU:\Software\Microsoft\Office\16.0\Outlook\Security'

# Registry path for Office-wide security settings (per-user)
$officeSecurityPath = 'HKCU:\Software\Microsoft\Office\16.0\Common\Security'

# Trusted sites hashtable: Key = hostname or UNC path, Value = Zone (1 = Intranet, 2 = Trusted)
# !! CUSTOMIZE these entries to match your environment before deploying !!
$trustedSites = @{
    'file://fileservername.domain' = 1
    'file://internal.local'        = 1
    'server.internal.local'        = 1
    'company.sharepoint.com'       = 1
}

#endregion

#region --- Detection Logic ---

function Invoke-Detection {
    [CmdletBinding()]
    param()

    $compliance = $true

    Write-Verbose 'Starting compliance detection...'

    # --- Check trusted sites in ZoneMap ---
    foreach ($site in $trustedSites.Keys) {
        try {
            $existingValue = Get-ItemProperty -Path $zoneMapPath -Name $site -ErrorAction Stop
            if ($existingValue.$site -ne $trustedSites[$site]) {
                Write-Verbose "ZoneMap entry mismatch for '$site'. Expected: $($trustedSites[$site]), Found: $($existingValue.$site)"
                $compliance = $false
            }
            else {
                Write-Verbose "ZoneMap entry OK for '$site'."
            }
        }
        catch {
            Write-Verbose "ZoneMap entry missing for '$site'."
            $compliance = $false
        }
    }

    # --- Check Outlook DisableHyperlinkWarning ---
    try {
        $outlookHyperlinkWarning = Get-ItemProperty -Path $outlookSecurityPath -Name 'DisableHyperlinkWarning' -ErrorAction Stop
        if ($outlookHyperlinkWarning.DisableHyperlinkWarning -ne 1) {
            Write-Verbose "Outlook DisableHyperlinkWarning is NOT set to 1. Current value: $($outlookHyperlinkWarning.DisableHyperlinkWarning)"
            $compliance = $false
        }
        else {
            Write-Verbose 'Outlook DisableHyperlinkWarning is correctly set to 1.'
        }
    }
    catch {
        Write-Verbose 'Outlook DisableHyperlinkWarning registry value is missing.'
        $compliance = $false
    }

    # --- Check Office-wide DisableHyperlinkWarning ---
    try {
        $officeHyperlinkWarning = Get-ItemProperty -Path $officeSecurityPath -Name 'DisableHyperlinkWarning' -ErrorAction Stop
        if ($officeHyperlinkWarning.DisableHyperlinkWarning -ne 1) {
            Write-Verbose "Office DisableHyperlinkWarning is NOT set to 1. Current value: $($officeHyperlinkWarning.DisableHyperlinkWarning)"
            $compliance = $false
        }
        else {
            Write-Verbose 'Office DisableHyperlinkWarning is correctly set to 1.'
        }
    }
    catch {
        Write-Verbose 'Office DisableHyperlinkWarning registry value is missing.'
        $compliance = $false
    }

    # --- Report result ---
    if ($compliance) {
        Write-Output 'Compliant'
        exit 0
    }
    else {
        Write-Output 'Non-Compliant'
        exit 1
    }
}

#endregion

#region --- Remediation Logic ---

function Invoke-Remediation {
    [CmdletBinding()]
    param()

    Write-Verbose 'Starting remediation...'

    # --- Ensure ZoneMap registry path exists ---
    try {
        if (-not (Test-Path -Path $zoneMapPath)) {
            Write-Verbose "Creating ZoneMap path: $zoneMapPath"
            New-Item -Path $zoneMapPath -Force -ErrorAction Stop | Out-Null
        }
    }
    catch {
        Write-Error "Failed to create ZoneMap registry path '$zoneMapPath'. Error: $_"
        exit 1
    }

    # --- Add or update trusted sites in ZoneMap ---
    foreach ($site in $trustedSites.Keys) {
        try {
            New-ItemProperty -Path $zoneMapPath -Name $site -Value $trustedSites[$site] `
                -PropertyType DWord -Force -ErrorAction Stop | Out-Null
            Write-Verbose "Set ZoneMap entry: '$site' = $($trustedSites[$site])"
        }
        catch {
            Write-Warning "Failed to set ZoneMap entry for '$site'. Error: $_"
        }
    }

    # --- Ensure Outlook security path exists and set DisableHyperlinkWarning ---
    try {
        if (-not (Test-Path -Path $outlookSecurityPath)) {
            Write-Verbose "Creating Outlook security registry path: $outlookSecurityPath"
            New-Item -Path $outlookSecurityPath -Force -ErrorAction Stop | Out-Null
        }
        New-ItemProperty -Path $outlookSecurityPath -Name 'DisableHyperlinkWarning' -Value 1 `
            -PropertyType DWord -Force -ErrorAction Stop | Out-Null
        Write-Verbose 'Outlook DisableHyperlinkWarning set to 1.'
    }
    catch {
        Write-Error "Failed to configure Outlook hyperlink warning setting. Error: $_"
        exit 1
    }

    # --- Ensure Office security path exists and set DisableHyperlinkWarning ---
    try {
        if (-not (Test-Path -Path $officeSecurityPath)) {
            Write-Verbose "Creating Office security registry path: $officeSecurityPath"
            New-Item -Path $officeSecurityPath -Force -ErrorAction Stop | Out-Null
        }
        New-ItemProperty -Path $officeSecurityPath -Name 'DisableHyperlinkWarning' -Value 1 `
            -PropertyType DWord -Force -ErrorAction Stop | Out-Null
        Write-Verbose 'Office DisableHyperlinkWarning set to 1.'
    }
    catch {
        Write-Error "Failed to configure Office hyperlink warning setting. Error: $_"
        exit 1
    }

    Write-Output 'Remediation applied successfully.'
    exit 0
}

#endregion

#region --- Entry Point ---

switch ($Mode) {
    'Detect'    { Invoke-Detection }
    'Remediate' { Invoke-Remediation }
}

#endregion
🐙 GitHub
PowerShellMicrosoft IntuneProactive RemediationWindows Registry

Fix Office Apps Defaulting to ODS/ODT Format with Intune Proactive Remediation

Detects and remediates Office 365 applications (Excel, Word, PowerPoint) defaulting to open document formats instead of native Office formats (XLSX, DOCX, PPTX) using Intune Proactive Remediation.

📖 Full guide: Fix Office Apps Defaulting to ODS/ODT Format with Intune Proactive Remediation
<#
.SYNOPSIS
    Detects and remediates incorrect default file formats in Office 365 applications (Excel, Word, PowerPoint).

.DESCRIPTION
    This script combines detection and remediation logic for an Intune Proactive Remediation package.
    It checks whether Excel, Word, and PowerPoint are configured to use their native Office file formats
    (XLSX, DOCX, PPTX) rather than open document formats (ODS, ODT, ODP).

    When deployed via Intune Proactive Remediation:
      - The DETECTION phase checks the HKCU registry keys for each Office application's DefaultFormat value.
        If any value is incorrect, the script exits with code 1 to trigger remediation.
      - The REMEDIATION phase sets the correct DefaultFormat registry values for all three applications:
          Excel  -> 51   (XLSX)
          Word   -> DOCX (string)
          PowerPoint -> 1 (PPTX)

    This script should be split into two separate .ps1 files for Intune deployment:
      - Detect-OfficeDefaultFormat.ps1  (Detection script)
      - Remediate-OfficeDefaultFormat.ps1 (Remediation script)

    Both scripts are included below, clearly separated by region blocks for easy extraction.

.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 detection locally to check current Office default format settings:
    .\Detect-OfficeDefaultFormat.ps1

    # Run remediation locally to correct Office default format settings:
    .\Remediate-OfficeDefaultFormat.ps1

    # In Intune, upload each script separately under:
    # Devices > Scripts and remediations > Create > Proactive remediation
#>

#region -------------------------------------------------------
# DETECTION SCRIPT: Detect-OfficeDefaultFormat.ps1
# Deploy this block as your Intune Proactive Remediation DETECTION script.
# Exit 0 = compliant | Exit 1 = non-compliant (triggers remediation)
#---------------------------------------------------------------

[CmdletBinding()]
param()

# Collect names of applications with incorrect default format settings
$incorrectSettings = @()

try {
    # --- Excel: DefaultFormat 51 = XLSX ---
    $excelKey = 'HKCU:\Software\Microsoft\Office\16.0\Excel\Options'
    $excelValue = Get-ItemProperty -Path $excelKey -Name 'DefaultFormat' -ErrorAction SilentlyContinue

    if ($null -eq $excelValue -or $excelValue.DefaultFormat -ne 51) {
        $incorrectSettings += 'Excel (expected 51 for XLSX)'
    }

    # --- Word: DefaultFormat 'DOCX' (string) = DOCX ---
    $wordKey = 'HKCU:\Software\Microsoft\Office\16.0\Word\Options'
    $wordValue = Get-ItemProperty -Path $wordKey -Name 'DefaultFormat' -ErrorAction SilentlyContinue

    if ($null -eq $wordValue -or $wordValue.DefaultFormat -ne 'DOCX') {
        $incorrectSettings += 'Word (expected DOCX string)'
    }

    # --- PowerPoint: DefaultFormat 1 = PPTX ---
    $pptKey = 'HKCU:\Software\Microsoft\Office\16.0\PowerPoint\Options'
    $pptValue = Get-ItemProperty -Path $pptKey -Name 'DefaultFormat' -ErrorAction SilentlyContinue

    if ($null -eq $pptValue -or $pptValue.DefaultFormat -ne 1) {
        $incorrectSettings += 'PowerPoint (expected 1 for PPTX)'
    }

    if ($incorrectSettings.Count -gt 0) {
        Write-Host "Non-compliant: Incorrect default format detected for: $($incorrectSettings -join ', ')"
        Exit 1
    }
    else {
        Write-Host 'Compliant: All Office applications are using the correct native default file format.'
        Exit 0
    }
}
catch {
    Write-Host "Detection error: $($_.Exception.Message)"
    Exit 1
}

#endregion


#region -------------------------------------------------------
# REMEDIATION SCRIPT: Remediate-OfficeDefaultFormat.ps1
# Deploy this block as your Intune Proactive Remediation REMEDIATION script.
# This script corrects the DefaultFormat registry values for Excel, Word, and PowerPoint.
#---------------------------------------------------------------

<#
[CmdletBinding()]
param()

try {
    # --- Set Excel default format to XLSX (value: 51) ---
    $excelKey = 'HKCU:\Software\Microsoft\Office\16.0\Excel\Options'
    if (-not (Test-Path $excelKey)) {
        New-Item -Path $excelKey -Force | Out-Null
    }
    Set-ItemProperty -Path $excelKey -Name 'DefaultFormat' -Value 51 -Type DWord
    Write-Host 'Excel: DefaultFormat set to 51 (XLSX).'

    # --- Set Word default format to DOCX (value: 'DOCX' string) ---
    $wordKey = 'HKCU:\Software\Microsoft\Office\16.0\Word\Options'
    if (-not (Test-Path $wordKey)) {
        New-Item -Path $wordKey -Force | Out-Null
    }
    Set-ItemProperty -Path $wordKey -Name 'DefaultFormat' -Value 'DOCX' -Type String
    Write-Host 'Word: DefaultFormat set to DOCX.'

    # --- Set PowerPoint default format to PPTX (value: 1) ---
    $pptKey = 'HKCU:\Software\Microsoft\Office\16.0\PowerPoint\Options'
    if (-not (Test-Path $pptKey)) {
        New-Item -Path $pptKey -Force | Out-Null
    }
    Set-ItemProperty -Path $pptKey -Name 'DefaultFormat' -Value 1 -Type DWord
    Write-Host 'PowerPoint: DefaultFormat set to 1 (PPTX).'

    Write-Host 'Remediation complete: Default formats corrected for Excel, Word, and PowerPoint.'
    Exit 0
}
catch {
    Write-Host "Remediation error: $($_.Exception.Message)"
    Exit 1
}
#>

#endregion
🐙 GitHub
PowerShellWindows RegistryMicrosoft Intune Win32 App Detection

Intune Win32 App Detection Rule Validator

Validates and generates version-aware registry detection logic for Intune Win32 apps to prevent endless reinstall loops caused by auto-updating software.

📖 Full guide: Intune Win32 App Keeps Reinstalling? Fix the Endless Loop for Good
<#
.SYNOPSIS
    Validates Intune Win32 app registry detection rules to prevent endless reinstall loops.

.DESCRIPTION
    This script addresses the common Intune Win32 app issue where auto-updating software causes
    an endless reinstall loop due to exact-version detection rules. Instead of checking for an
    exact version (which breaks when the app self-updates), this script:

      - Queries the local registry for an installed application's DisplayVersion
      - Compares the installed version against a minimum required version
      - Returns exit code 0 (detected) if installed version >= minimum version
      - Returns exit code 1 (not detected) if the app is missing or below minimum version

    This script is designed to be used as a Custom Script detection rule inside an Intune
    Win32 app deployment. It replaces brittle 'Equals' version checks with a safe
    'Greater Than or Equal To' comparison that survives auto-updates.

    Supported scenarios:
      - Google Chrome, Zoom, Teams Machine-Wide Installer, VPN clients, security agents
      - Any Win32 app that self-updates outside of Intune control

.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 locally to test detection for an app with a known GUID and minimum version:
    .\Invoke-Win32AppDetection.ps1 -AppGuid '{12345678-1234-1234-1234-123456789012}' -MinimumVersion '1.5.3.2501222'

.EXAMPLE
    # Use as Intune custom script detection (no parameters needed if values are hardcoded):
    # Deploy this script as the Detection Rule for a Win32 app in Intune.
    # Intune interprets exit code 0 as Detected, any other code as Not Detected.
    .\Invoke-Win32AppDetection.ps1
#>

[CmdletBinding()]
param (
    # The GUID of the application as found in the Uninstall registry key.
    # Example: '{12345678-1234-1234-1234-123456789012}'
    # Leave blank to use the hardcoded default below (recommended for Intune deployment).
    [Parameter(Mandatory = $false)]
    [string]$AppGuid = '{YOUR-APP-GUID-HERE}',

    # The minimum acceptable version of the application.
    # Detection passes if installed version >= this value.
    [Parameter(Mandatory = $false)]
    [string]$MinimumVersion = '1.5.3.2501222'
)

#region --- Configuration ---

# Registry paths to check (covers both 32-bit and 64-bit app registrations)
$RegistryPaths = @(
    "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\$AppGuid",
    "HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\$AppGuid"
)

#endregion

#region --- Helper Functions ---

function Get-InstalledVersion {
    <#
    .SYNOPSIS
        Retrieves the DisplayVersion value from the Uninstall registry key for a given app GUID.
    #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string[]]$RegistryPaths
    )

    foreach ($path in $RegistryPaths) {
        if (Test-Path -Path $path) {
            try {
                $regItem = Get-ItemProperty -Path $path -ErrorAction Stop
                if ($regItem.DisplayVersion) {
                    Write-Verbose "Found DisplayVersion '$($regItem.DisplayVersion)' at path: $path"
                    return $regItem.DisplayVersion
                }
            }
            catch {
                Write-Verbose "Could not read registry path '$path': $_"
            }
        }
    }

    # App not found in any registry path
    return $null
}

function Compare-AppVersion {
    <#
    .SYNOPSIS
        Compares two version strings and returns true if InstalledVersion >= MinimumVersion.
    .DESCRIPTION
        Uses [System.Version] for accurate multi-part version comparison.
        Falls back gracefully if version strings cannot be parsed.
    #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$InstalledVersion,

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

    try {
        $installed = [System.Version]$InstalledVersion
        $minimum   = [System.Version]$MinimumVersion

        Write-Verbose "Comparing installed version [$installed] >= minimum version [$minimum]"
        return ($installed -ge $minimum)
    }
    catch {
        Write-Warning "Version comparison failed. InstalledVersion='$InstalledVersion', MinimumVersion='$MinimumVersion'. Error: $_"
        # If we cannot parse versions, treat as not detected to be safe
        return $false
    }
}

#endregion

#region --- Main Detection Logic ---

try {
    Write-Verbose "Starting Win32 app detection for GUID: $AppGuid"
    Write-Verbose "Minimum required version: $MinimumVersion"

    # Step 1: Attempt to retrieve the installed version from the registry
    $installedVersion = Get-InstalledVersion -RegistryPaths $RegistryPaths

    if ($null -eq $installedVersion) {
        # App is not installed at all — detection fails
        Write-Verbose "Application not found in registry. Reporting as NOT DETECTED."
        exit 1
    }

    Write-Verbose "Installed version detected: $installedVersion"

    # Step 2: Perform version-aware comparison (>= minimum, not == exact)
    # This is the critical fix: auto-updates increment the version, but detection
    # should still pass as long as the installed version meets the minimum bar.
    $isDetected = Compare-AppVersion -InstalledVersion $installedVersion -MinimumVersion $MinimumVersion

    if ($isDetected) {
        # Version meets or exceeds the minimum — report as DETECTED
        Write-Host "DETECTED: Version $installedVersion is >= minimum $MinimumVersion"
        exit 0
    }
    else {
        # Version is below the minimum — report as NOT DETECTED, trigger reinstall
        Write-Host "NOT DETECTED: Version $installedVersion is below minimum $MinimumVersion"
        exit 1
    }
}
catch {
    # Unhandled exception — treat as not detected to avoid false positives
    Write-Warning "Unexpected error during detection: $_"
    exit 1
}

#endregion
🐙 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 IntuneProactive Remediations

Intune Secure Boot and OS Compliance Detection Script

Detects Secure Boot status and OS build version on Windows 11 devices for use as an Intune Proactive Remediation detection script to assess fleet readiness ahead of the 2026 Secure Boot certificate expiry.

<#
.SYNOPSIS
    Detects Secure Boot status and OS build version for Intune Proactive Remediation compliance assessment.

.DESCRIPTION
    This script is designed to be deployed as an Intune Proactive Remediation (Remediations) detection script
    to assess Windows 11 device readiness ahead of the Microsoft Secure Boot certificate rotation in 2026.

    It performs the following checks on each managed endpoint:
      - Queries Secure Boot status using Confirm-SecureBootUEFI
      - Retrieves the current OS build number and Windows version
      - Outputs a structured JSON object for consumption by the Intune Remediations engine

    Devices where Secure Boot is disabled or unsupported, or where the OS build is below the
    acceptable minimum, can be identified from the Intune Remediations results and targeted for
    remediation before the certificate expiry deadline in June 2026.

    Deploy this script under:
      Intune > Devices > Remediations > Create > Detection Script

    Results are visible in the Intune portal under the Remediations node and can be exported
    to CSV for further filtering and reporting.

.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 locally on a single device to verify output before deploying via Intune:
    .\Detect-SecureBootCompliance.ps1

    # Expected output (JSON):
    # {"ComputerName":"DESKTOP-ABC123","SecureBootEnabled":true,"OSVersion":"22H2","OSBuild":"22621"}

.EXAMPLE
    # Deploy as an Intune Proactive Remediation Detection Script:
    # 1. Navigate to Intune > Devices > Remediations > + Create
    # 2. Paste this script into the Detection Script field
    # 3. Set 'Run this script using the logged-on credentials' to No (run as SYSTEM)
    # 4. Assign to a device group containing your Windows 11 fleet
    # 5. Review results under the Remediations node and export to CSV for analysis
#>

[CmdletBinding()]
param()

# ---------------------------------------------------------------------------
# Step 1: Determine Secure Boot status
# Confirm-SecureBootUEFI returns:
#   $true  - Secure Boot is enabled and active
#   $false - Secure Boot is supported but currently disabled
#   throws - Hardware does not support Secure Boot (legacy BIOS or unsupported firmware)
# ---------------------------------------------------------------------------
try {
    $SecureBoot = Confirm-SecureBootUEFI
} catch {
    # Device does not support Secure Boot (e.g., non-UEFI hardware or CSM-only boot)
    $SecureBoot = "Unsupported"
}

# ---------------------------------------------------------------------------
# Step 2: Collect OS version information
# OsBuildNumber surfaces the numeric build (e.g., 22621 for Windows 11 22H2)
# WindowsVersion surfaces the marketing version string (e.g., "22H2")
# Get-ComputerInfo can be slow; acceptable in a detection script context.
# ---------------------------------------------------------------------------
try {
    $ComputerInfo = Get-ComputerInfo -ErrorAction Stop
    $OSBuild    = $ComputerInfo.OsBuildNumber
    $OSVersion  = $ComputerInfo.WindowsVersion
} catch {
    # Fallback to registry-based retrieval if Get-ComputerInfo fails
    $OSBuild   = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name CurrentBuildNumber -ErrorAction SilentlyContinue).CurrentBuildNumber
    $OSVersion = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name DisplayVersion   -ErrorAction SilentlyContinue).DisplayVersion
}

# ---------------------------------------------------------------------------
# Step 3: Build structured output object
# The JSON output is consumed by Intune Remediations for reporting.
# Fields:
#   ComputerName      - Hostname of the device
#   SecureBootEnabled - True / False / "Unsupported"
#   OSVersion         - Windows release version string (e.g., "23H2")
#   OSBuild           - Numeric OS build number (e.g., 22631)
# ---------------------------------------------------------------------------
$Output = [PSCustomObject]@{
    ComputerName      = $env:COMPUTERNAME
    SecureBootEnabled = $SecureBoot
    OSVersion         = $OSVersion
    OSBuild           = $OSBuild
}

# ---------------------------------------------------------------------------
# Step 4: Emit compact JSON to stdout for Intune to capture
# -Compress removes whitespace to keep the output on a single line,
# which is friendlier for Intune's output field length constraints.
# ---------------------------------------------------------------------------
Write-Output ($Output | ConvertTo-Json -Compress)

# ---------------------------------------------------------------------------
# Step 5: Exit code convention for Intune Proactive Remediations
# Exit 0 = detected no issue (compliant) — no remediation script will run
# Exit 1 = issue detected (non-compliant) — triggers the paired remediation script
#
# Evaluate compliance criteria:
#   - Secure Boot must be enabled (not False or Unsupported)
#   - OS build should meet the minimum required threshold
#     Update $MinimumBuild to reflect your organisation's current baseline.
# ---------------------------------------------------------------------------
$MinimumBuild = 22621  # Windows 11 22H2 — adjust to your required minimum

$isSecureBootCompliant = ($SecureBoot -eq $true)
$isBuildCompliant      = ($OSBuild -ge $MinimumBuild)

if ($isSecureBootCompliant -and $isBuildCompliant) {
    # Device meets all compliance criteria — no remediation needed
    exit 0
} else {
    # Device is non-compliant — Intune will trigger the paired remediation script
    exit 1
}
🐙 GitHub
PowerShellMicrosoft IntuneWin32 App Packaging

Deploy Always-Updated Google Chrome via Intune Win32 App

Downloads and silently installs the latest Google Chrome directly from Google's official source, designed for Intune Win32 app deployment via Company Portal.

📖 Full guide: Deploy Always-Updated Google Chrome via Intune Company Portal (Win32 App)
<#
.SYNOPSIS
    Downloads and silently installs the latest version of Google Chrome from Google's official source.

.DESCRIPTION
    This script is designed to be packaged as an Intune Win32 app and deployed via Microsoft Endpoint Manager
    (Microsoft Intune) Company Portal. It fetches the most current Chrome installer directly from Google's
    official CDN URL, which always points to the latest available version. The installer runs silently
    with no user interaction required, and the installer file is cleaned up after installation.

    By using the dynamic Google CDN URL instead of a static versioned installer, this approach ensures
    that every device enrollment or app deployment always receives the latest secure version of Chrome,
    eliminating the need for manual Intune app updates each time a new Chrome version is released.

    Intended usage:
      - Install Command : powershell.exe -ExecutionPolicy Bypass -File InstallChrome.ps1
      - Uninstall Command: powershell.exe -ExecutionPolicy Bypass -File UninstallChrome.ps1
      - Detection Rule  : File or registry rule confirming chrome.exe presence in Program Files\Google\Chrome

.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 locally or via Intune Win32 install command:
    powershell.exe -ExecutionPolicy Bypass -File InstallChrome.ps1

.EXAMPLE
    # Run uninstall script via Intune Win32 uninstall command:
    powershell.exe -ExecutionPolicy Bypass -File UninstallChrome.ps1
#>

[CmdletBinding()]
param()

#region --- INSTALL SCRIPT ---

# Define the official Google CDN URL that always resolves to the latest Chrome installer
$chromeInstallerUrl = "https://dl.google.com/chrome/install/latest/chrome_installer.exe"

# Define a temporary staging folder and full path for the downloaded installer
$installerFolder = "C:\Temp"
$installerPath   = Join-Path -Path $installerFolder -ChildPath "chrome_installer.exe"

try {
    # Ensure the temporary staging folder exists; create it silently if it does not
    if (-Not (Test-Path -Path $installerFolder)) {
        Write-Verbose "Staging folder '$installerFolder' not found. Creating it now."
        New-Item -ItemType Directory -Path $installerFolder -Force | Out-Null
    }

    # Download the latest Chrome installer from the official Google source
    Write-Verbose "Downloading Chrome installer from: $chromeInstallerUrl"
    Invoke-WebRequest -Uri $chromeInstallerUrl -OutFile $installerPath -UseBasicParsing

    # Verify the installer was downloaded successfully before proceeding
    if (-Not (Test-Path -Path $installerPath)) {
        throw "Installer download failed. File not found at '$installerPath'."
    }

    # Execute the Chrome installer silently with no user prompts
    Write-Verbose "Starting silent Chrome installation..."
    $process = Start-Process -FilePath $installerPath -ArgumentList "/silent /install" -Wait -PassThru

    if ($process.ExitCode -ne 0) {
        throw "Chrome installer exited with non-zero exit code: $($process.ExitCode)."
    }

    Write-Output "Google Chrome installed successfully."
}
catch {
    Write-Error "An error occurred during Chrome installation: $_"
    exit 1
}
finally {
    # Always attempt to clean up the installer file regardless of success or failure
    if (Test-Path -Path $installerPath) {
        Write-Verbose "Removing installer file: $installerPath"
        Remove-Item -Path $installerPath -Force -ErrorAction SilentlyContinue
    }
}

#endregion --- INSTALL SCRIPT ---
🐙 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.