39 production-tested scripts for Intune, Entra ID, Exchange Online and Windows — detection & remediation pairs, Graph automations and reporting tools. Every script links to the full guide that explains when (and when not) to run it.
Exports a tenant report of Intune Windows PowerShell script assignments, resolving built-in targets (All Devices/All Users) and included/excluded Entra groups for audit-ready change reviews.
AZ-104 Endpoint Architect's Blueprint for Azure & M365 Automation
A GitHub repository for Azure administration and M365 automation, focusing on endpoint architect needs, featuring a PowerShell script for secure Azure infrastructure deployment and a PHP-based M365 SaaS engine frontend.
### FILE: index.php
<?php
// This is a placeholder for the M365 SaaS Engine frontend dashboard.
// It demonstrates how to fetch data from Microsoft Graph and render it using the provided functions.
// In a real application, more sophisticated logic, error handling, and UI components would be present.
// Assume $ms (Microsoft Graph service-architect-automation
Automated PowerShell script utilizing Microsoft Graph v2 SDK to audit endpoint compliance states, hardware metrics, and synchronization health across Microsoft Intune fleets.
### FILE: index.php
<?php
// This file serves as the main dashboard for the M365 SaaS engine.
// It orchestrates calls to Microsoft Graph via the provided $ms object and renders UI cards.
// Ensure the user is authenticated and has an access token.
if (!isset($_SESSION['ms_access_token'])) {
// Redirect to login or show an error
die('Authentication required. Please log in.');
}
$accessToken = $_SESSION['ms_access_token'];
// --- Example 1: Fetching Intune Device Compliance Policies ---
$policyEndpoint = '/deviceManagement/deviceCompliancePolicies';
$policiesData = $ms->graphCall($policyEndpoint, $accessToken);
if (isset($policiesData['value']) && is_array($policiesData['value'])) {
$activePolicies = count($policiesData['value']);
render_premium_card(
'Active Intune Policies',
(string)$activePolicies,
null, // No trend value for this example
'up', // Assume 'up' is good for policy count
'🛡️'
);
} else {
render_premium_card('Active Intune Policies', 'N/A', null, 'down', '⚠️');
error_log('Failed to fetch Intune policies: ' . json_encode($policiesData));
}
// --- Example 2: Fetching Dynamic Device Groups ---
$groupEndpoint = '/groups?$filter=groupTypes/any(c:c eq \'DynamicMembership\')';
$groupsData = $ms->graphCall($groupEndpoint, $accessToken);
if (isset($groupsData['value']) && is_array($groupsData['value'])) {
$dynamicGroups = count($groupsData['value']);
render_premium_card(
'Dynamic Device Groups',
(string)$dynamicGroups,
null,
'up',
'👥'
);
} else {
render_premium_card('Dynamic Device Groups', 'N/A', null, 'down', '⚠️');
error_log('Failed to fetch dynamic groups: ' . json_encode($groupsData));
}
// --- Example 3: Displaying Recent Sign-in Failures (Placeholder) ---
// In a real scenario, you would query Entra ID sign-in logs via Graph.
// For demonstration, let's simulate some data or fetch a simplified view.
// $signInLogsEndpoint = '/auditLogs/signIns?$filter=status/errorCode ne 0&$top=5';
// $failedSignIns = $ms->graphCall($signInLogsEndpoint, $accessToken);
// For this example, let's use a static card.
render_premium_card(
'Recent Sign-in Failures',
'5',
'20% increase',
'down',
'❌'
);
// --- Integration with PowerShell Automation (Conceptual) ---
// If a user clicks a button to 'Assign Policy', the PHP backend would:
// 1. Validate input.
// 2. Potentially call the PowerShell script (e.g., via a system call or Azure Function).
// 3. Or, directly make the Graph API call for assignment using $ms->graphCall and a POST method.
// Example: $ms->graphCall("/deviceManagement/deviceCompliancePolicies/{policyId}/assignments", $accessToken, 'POST', $assignmentBody);
// The PowerShell script 'Assign-IntunePolicyToDynamicGroup.ps1' would represent a backend automation
// that could be triggered by such a PHP interface or run on a schedule.
?>
### FILE: index.php
<?php
// Placeholder for access token from session
$accessToken = $_SESSION['ms_access_token'];
// Function to call the Azure AI resource model endpoint and deploy an AI model
function deployAIModel($modelName) {
global $ms, $accessToken;
$endpoint = "https://graph.microsoft.com/v1.0/resourceModel";
$body = [
'modelName' => $modelName
];
$response = $ms->graphCall($endpoint, $accessToken, 'POST', $body);
if ($response) {
render_premium_card("Model Deployment", "Model $modelName deployed successfully", null, 'up', '🚀', 100);
} else {
echo "Error deploying model.";
}
}
// Calling function to deploy the model
$modelName = "ContosoAI";
deployAIModel($modelName);
?>
### FILE: scripts/Automation.ps1
<#
.SYNOPSIS
Deploys an AI model using Microsoft Graph API.
.DESCRIPTION
This script integrates with the Microsoft Graph API to manage Azure AI resources, specifically to deploy an AI model.
.EXAMPLE
Deploy-AIModel -modelName 'ContosoAI'
.NOTES
Author: Souhaiel Morhag
Company: MSEndpoint.com
Blog: https://msendpoint.com
Academy: https://app.msendpoint.com/academy
LinkedIn: https://linkedin.com/in/souhaiel-morhag
GitHub: https://github.com/Msendpoint
License: MIT
#>
Import-Module Microsoft.Graph
# Connect to Microsoft Graph with necessary scopes
Connect-MgGraph -Scopes "AI.ReadWrite.All", "Directory.Read.All"
function Deploy-AIModel {
[CmdletBinding(SupportsShouldProcess=$true)]
Param (
[Parameter(Mandatory=$true)]
[string]$modelName
)
Try {
# Invoke Graph API to deploy AI model
Invoke-MgGraphRequest -Uri "https://graph.microsoft.com/v1.0/resourceModel" `
-Method POST `
-Body @{modelName = $modelName} | Out-Null
Write-Output "Model $modelName deployed successfully"
} Catch {
# Error handling for failed deployment
Write-Error "Error deploying model: $_.Exception.Message"
exit 1
}
}
# Example of deploying an AI model
Deploy-AIModel -modelName "ContosoAI" -WhatIf
### FILE: index.php
<?php
// Logic to fetch data from Graph and call render_premium_card multiple times to build the dashboard...
$accessToken = $_SESSION['ms_access_token'];
$userEndpoint = 'https://graph.microsoft.com/v1.0/users';
$response = $ms->graphCall($userEndpoint, $accessToken);
// Render cards based on response data
render_premium_card('User Creation', count($response['value']), 'Up', 'up', '👤', 70);
?>
### FILE: scripts/Automation.ps1
<#
.SYNOPSIS
Automates user creation and role assignment using Microsoft Graph API.
.DESCRIPTION
This script creates a user in Azure AD with the given UserPrincipalName, DisplayName, and assigns a role if specified using the Microsoft Graph PowerShell module.
.EXAMPLE
.
param (
[string]$UserPrincipalName = 'jdoe@example.com',
[string]$DisplayName = 'John Doe',
[string]$Role = 'User'
)
.NOTES
Author: Souhaiel Morhag
Company: MSEndpoint.com
Blog: https://msendpoint.com
Academy: https://app.msendpoint.com/academy
LinkedIn: https://linkedin.com/in/souhaiel-morhag
GitHub: https://github.com/Msendpoint
License: MIT
#>
param (
[string]$UserPrincipalName,
[string]$DisplayName,
[string]$Role
)
Try {
Write-Output "Creating user $UserPrincipalName"
$user = @{
"UserPrincipalName" = $UserPrincipalName
"DisplayName" = $DisplayName
"MailNickname" = $UserPrincipalName.Split('@')[0]
"AccountEnabled" = $true
}
New-MgUser -BodyParameter $user
Write-Output "User $UserPrincipalName created successfully"
If ($Role) {
Write-Output "Assigning role $Role to $UserPrincipalName"
# Add role assignment logic here
}
} Catch {
Write-Output "Failed to create user: $_"
exit 1
}
exit 0
A PowerShell and M365 SaaS toolkit to discover EWS-dependent applications, correlate audit logs against Entra ID app registrations, manage EwsAllowedAppIDs containment, and execute a phased mailbox-level EWS cutover ahead of the October 2026 retirement.
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.
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.
### 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
}
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).
### 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
}
PowerShellMicrosoft Teams PowerShell ModuleMicrosoft GraphPHP
Teams Copilot Chat Governance Toolkit for GCC, GCC High & DoD
PowerShell audit tooling and a Microsoft 365 SaaS Engine dashboard for tracking and controlling Teams Copilot Chat rollout compliance across US Government cloud instances (GCC, GCC High, DoD).
### FILE: scripts/Audit-CopilotChatEnablement.ps1
<#
.SYNOPSIS
Cross-cloud audit of Microsoft Teams Copilot Chat enablement signals across GCC, GCC High, and DoD tenants.
.DESCRIPTION
This script connects to a specified US Government Community Cloud instance (GCC, GCC High, or DoD)
using the MicrosoftTeams PowerShell module and enumerates all Teams Messaging Policies and Meeting
Policies to determine the current enablement state of Copilot Chat surfaces (1:1/Group Chat, Channels,
Calls, Meetings).
Because Teams PowerShell sessions are cloud-instance-specific and credentials do not roam across
sovereign cloud boundaries, this script must be run once per cloud instance connection by an admin
holding the appropriate role in that tenant.
The report flags policies where transcription-dependent Copilot features (Calls/Meetings recap) may
be blocked due to 'AllowTranscription' being disabled at the tenant or policy level -- a common
inherited default in DoD-adjacent CMMC/NIST 800-171 hardening baselines.
IMPORTANT: Property names such as AllowCopilotChat and AllowChannelSummary reflect the schema at
time of writing (Sep 2026) and are subject to change post-GA. Always validate against:
Get-CsTeamsMessagingPolicy | Get-Member -MemberType Property
before relying on this script's output in a compliance report.
.EXAMPLE
.\Audit-CopilotChatEnablement.ps1 -CloudInstance GCCHigh -TenantAdminUPN admin@contoso.us
Connects to the GCC High cloud instance as admin@contoso.us and exports a CSV audit report to the
default C:\Reports path.
.EXAMPLE
.\Audit-CopilotChatEnablement.ps1 -CloudInstance DoD -TenantAdminUPN admin@contoso.mil -ReportPath 'D:\Audits\dod_copilot_audit.csv'
Connects to the DoD cloud instance and writes the report to a custom path.
.NOTES
Author: Souhaiel Morhag
Company: MSEndpoint.com
Blog: https://msendpoint.com
Academy: https://app.msendpoint.com/academy
LinkedIn: https://linkedin.com/in/souhaiel-morhag
GitHub: https://github.com/Msendpoint
License: MIT
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateSet('GCC','GCCHigh','DoD')]
[string]$CloudInstance,
[Parameter(Mandatory = $true)]
[string]$TenantAdminUPN,
[Parameter(Mandatory = $false)]
[string]$ReportPath = "C:\Reports\CopilotChat_Audit_$(Get-Date -Format 'yyyyMMdd_HHmm').csv"
)
$ErrorActionPreference = 'Stop'
$results = [System.Collections.Generic.List[Object]]::new()
# Map cloud instance to the correct Teams PowerShell admin endpoint (reference only —
# actual connection is handled via TeamsEnvironmentName below)
$cloudEndpointMap = @{
'GCC' = 'https://admin.teams.microsoft.com'
'GCCHigh' = 'https://admin.teams.microsoft.us'
'DoD' = 'https://admin.teams.microsoft.us'
}
try {
# Ensure the report directory exists before we attempt to write to it
$reportDir = Split-Path -Path $ReportPath -Parent
if ($reportDir -and -not (Test-Path -Path $reportDir)) {
New-Item -Path $reportDir -ItemType Directory -Force | Out-Null
}
Write-Host "[+] Connecting to Teams PowerShell — Cloud Instance: $CloudInstance ($($cloudEndpointMap[$CloudInstance]))" -ForegroundColor Cyan
$connectParams = @{
AccountId = $TenantAdminUPN
}
# GCC uses the standard commercial cloud endpoint implicitly; GCC High and DoD require
# explicit environment targeting so the module authenticates against the correct boundary
switch ($CloudInstance) {
'GCCHigh' { $connectParams['TeamsEnvironmentName'] = 'TeamsGCCH' }
'DoD' { $connectParams['TeamsEnvironmentName'] = 'TeamsDOD' }
}
Connect-MicrosoftTeams @connectParams
Write-Host "[+] Connected. Enumerating messaging and meeting policies..." -ForegroundColor Cyan
# Pull ALL messaging policies — Copilot Chat surface toggle lives here in current builds
$messagingPolicies = Get-CsTeamsMessagingPolicy
foreach ($policy in $messagingPolicies) {
# Property names below reflect current (Sep 2026) schema; validate against
# Get-CsTeamsMessagingPolicy | Get-Member if Microsoft renames properties post-GA
$copilotChatEnabled = $policy.AllowCopilotChat -as [bool]
$channelSummaryEnabled = $policy.AllowChannelSummary -as [bool]
$results.Add([PSCustomObject]@{
CloudInstance = $CloudInstance
RecordType = 'MessagingPolicy'
PolicyName = $policy.Identity
AllowCopilotChat = $copilotChatEnabled
AllowChannelSummary = $channelSummaryEnabled
IsGlobalPolicy = ($policy.Identity -eq 'Global')
AllowTranscription = $null
AllowCloudRecording = $null
CopilotDependencyMet = $null
AuditTimestamp = (Get-Date).ToString('o')
})
}
# Cross-reference meeting policies for the transcription dependency gate — Calls and
# Meetings Copilot recap features require AllowTranscription to be $true
$meetingPolicies = Get-CsTeamsMeetingPolicy
foreach ($mp in $meetingPolicies) {
$results.Add([PSCustomObject]@{
CloudInstance = $CloudInstance
RecordType = 'MeetingPolicy'
PolicyName = $mp.Identity
AllowCopilotChat = $null
AllowChannelSummary = $null
IsGlobalPolicy = ($mp.Identity -eq 'Global')
AllowTranscription = $mp.AllowTranscription -as [bool]
AllowCloudRecording = $mp.AllowCloudRecording -as [bool]
CopilotDependencyMet = ($mp.AllowTranscription -eq $true)
AuditTimestamp = (Get-Date).ToString('o')
})
}
Azure & M365 Copilot Agent Management and Audit Toolkit
A professional GitHub repository demonstrating how to manage and audit Azure Copilot agent interactions, verify policy configurations, and integrate M365 Copilot agent insights into a SaaS dashboard for architects.
### FILE: index.php
<?php
// Ensure user is authenticated and has a valid access token
if (!isset($_SESSION['ms_access_token'])) {
echo 'Access token is missing.';
exit;
}
// Fetch device compliance policies from Microsoft Graph
function fetchDeviceCompliancePolicies($ms, $accessToken) {
try {
$endpoint = 'https://graph.microsoft.com/v1.0/deviceManagement/deviceCompliancePolicies';
$response = $ms->graphCall($endpoint, $accessToken, 'GET');
return $response;
} catch (Exception $e) {
echo 'Error fetching compliance policies: ' . $e->getMessage();
return null;
}
}
// Retrieve the list
$compliancePolicies = fetchDeviceCompliancePolicies($ms, $_SESSION['ms_access_token']);
// Render premium card with fetched data
echo render_premium_card('Device Compliance Policies', json_encode($compliancePolicies));
?>
### FILE: scripts/Automation.ps1
<#
.SYNOPSIS
Retrieves and exports all devices under Intune management.
.DESCRIPTION
This script connects to Microsoft Graph using the MgGraph module, retrieves all managed devices, and exports the list to a CSV file.
.EXAMPLE
.\Automation.ps1
.NOTES
Author: Souhaiel Morhag
Company: MSEndpoint.com
Blog: https://msendpoint.com
Academy: https://app.msendpoint.com/academy
LinkedIn: https://linkedin.com/in/souhaiel-morhag
GitHub: https://github.com/Msendpoint
License: MIT
#>
try {
# Connect to Microsoft Graph
Connect-MgGraph -Scopes "DeviceManagementConfiguration.Read.All"
# Retrieve the list of managed devices
$devices = Get-MgDeviceManagementManagedDevice
# Export the devices to a CSV file
$devices | Export-Csv -Path "intune_devices.csv" -NoTypeInformation
Write-Output "Device list exported successfully to intune_devices.csv."
} catch {
Write-Error "Failed to export device list: $_.Exception.Message"
}
PowerShellMicrosoft GraphPHP
Intune Device Memory Management
PowerShell and SaaS integration for analyzing and displaying Intune device memory requirements.
<#
.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: $_"
}
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.
<#
.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 ---
Entra Conditional Access Policy Backup via Microsoft Graph
Exports all Microsoft Entra ID Conditional Access policies to a versioned JSON file for backup, audit, and recovery purposes using the Microsoft Graph PowerShell SDK.
<#
.SYNOPSIS
Exports all Microsoft Entra ID Conditional Access policies to a timestamped JSON backup file.
.DESCRIPTION
This script connects to Microsoft Graph using the Policy.Read.All and
Policy.ReadWrite.ConditionalAccess scopes, retrieves all Conditional Access
policies defined in the tenant, and exports them as a formatted JSON file.
The output file is named with a UTC timestamp to support versioned, point-in-time
backups. This script is intended to be used as a scheduled backup mechanism or
as a secondary validation layer alongside Microsoft Entra's native Backup and
Recovery feature.
Use cases include:
- Pre-change snapshots before modifying Conditional Access policies
- Scheduled nightly backups stored in source control (e.g., Git)
- Audit evidence for ISO 27001, SOC 2, or NIST CSF compliance reviews
- Recovery baseline when manual policy reconstruction is required
Requirements:
- PowerShell 7.x or Windows PowerShell 5.1
- Microsoft.Graph.Identity.SignIns module installed
- Entra ID P2, E5, or Entra Suite license (for full CA policy access)
- Sufficient permissions: Policy.Read.All (minimum); Policy.ReadWrite.ConditionalAccess if restores are planned
.NOTES
Author: Souhaiel Morhag
Company: MSEndpoint.com
Blog: https://msendpoint.com
Academy: https://app.msendpoint.com/academy
LinkedIn: https://linkedin.com/in/souhaiel-morhag
GitHub: https://github.com/Msendpoint
License: MIT
.EXAMPLE
# Run interactively with default output directory (script root)
.\Backup-EntraConditionalAccessPolicies.ps1
.EXAMPLE
# Specify a custom output directory
.\Backup-EntraConditionalAccessPolicies.ps1 -OutputPath 'C:\Backups\EntraCA'
.EXAMPLE
# Run non-interactively using a Managed Identity or pre-authenticated session
Connect-MgGraph -Identity
.\Backup-EntraConditionalAccessPolicies.ps1 -OutputPath 'D:\CABackups' -SkipConnect
#>
[CmdletBinding()]
param (
# Directory where the JSON backup file will be saved. Defaults to the script's own directory.
[Parameter(Mandatory = $false)]
[string]$OutputPath = $PSScriptRoot,
# Skip the Connect-MgGraph call if a session is already established (e.g., in automation pipelines).
[Parameter(Mandatory = $false)]
[switch]$SkipConnect
)
#region --- Prerequisites Check ---
# Ensure the required Graph module is available
if (-not (Get-Module -ListAvailable -Name 'Microsoft.Graph.Identity.SignIns')) {
Write-Error "Required module 'Microsoft.Graph.Identity.SignIns' is not installed. Run: Install-Module Microsoft.Graph.Identity.SignIns -Scope CurrentUser"
exit 1
}
# Import the module (suppress verbose output)
Import-Module Microsoft.Graph.Identity.SignIns -ErrorAction Stop
#endregion
#region --- Authentication ---
if (-not $SkipConnect) {
try {
Write-Verbose "Connecting to Microsoft Graph..."
# Request minimum required scopes for reading CA policies
Connect-MgGraph -Scopes "Policy.Read.All", "Policy.ReadWrite.ConditionalAccess" -ErrorAction Stop
Write-Verbose "Successfully connected to Microsoft Graph."
}
catch {
Write-Error "Failed to connect to Microsoft Graph. Error: $_"
exit 1
}
}
else {
Write-Verbose "Skipping Connect-MgGraph as -SkipConnect was specified."
# Validate that an active Graph session already exists
$context = Get-MgContext
if (-not $context) {
Write-Error "No active Microsoft Graph session found. Either remove -SkipConnect or authenticate first using Connect-MgGraph."
exit 1
}
Write-Verbose "Using existing Graph session for tenant: $($context.TenantId)"
}
#endregion
#region --- Output Directory Validation ---
try {
if (-not (Test-Path -Path $OutputPath)) {
Write-Verbose "Output directory does not exist. Creating: $OutputPath"
New-Item -ItemType Directory -Path $OutputPath -Force | Out-Null
}
}
catch {
Write-Error "Failed to create or access output directory '$OutputPath'. Error: $_"
exit 1
}
#endregion
#region --- Export Conditional Access Policies ---
try {
Write-Verbose "Retrieving all Conditional Access policies from Microsoft Graph..."
# Retrieve all CA policies; -All ensures pagination is handled automatically
$policies = Get-MgIdentityConditionalAccessPolicy -All -ErrorAction Stop
if (-not $policies -or $policies.Count -eq 0) {
Write-Warning "No Conditional Access policies found in the tenant. The backup file will be empty."
}
else {
Write-Verbose "Retrieved $($policies.Count) Conditional Access policy/policies."
}
}
catch {
Write-Error "Failed to retrieve Conditional Access policies. Error: $_"
exit 1
}
#endregion
#region --- Serialize and Write to File ---
try {
# Build a timestamped filename for versioned backups (UTC to avoid timezone ambiguity)
$timestamp = (Get-Date).ToUniversalTime().ToString('yyyyMMdd_HHmmss')
$outputFile = Join-Path -Path $OutputPath -ChildPath "ConditionalAccessPolicies_$timestamp`_UTC.json"
Write-Verbose "Serializing policies to JSON..."
# Convert to JSON with sufficient depth to capture nested conditions (e.g., grantControls, sessionControls)
$jsonContent = $policies | ConvertTo-Json -Depth 20 -ErrorAction Stop
# Write UTF-8 encoded file without BOM for compatibility with Git and downstream tools
[System.IO.File]::WriteAllText($outputFile, $jsonContent, [System.Text.UTF8Encoding]::new($false))
Write-Host "Backup complete." -ForegroundColor Green
Write-Host " Policies exported : $($policies.Count)" -ForegroundColor Cyan
Write-Host " Output file : $outputFile" -ForegroundColor Cyan
Write-Host " Timestamp (UTC) : $timestamp" -ForegroundColor Cyan
}
catch {
Write-Error "Failed to serialize or write the backup file. Error: $_"
exit 1
}
#endregion
#region --- Disconnect (optional, skip in automation contexts) ---
if (-not $SkipConnect) {
try {
Disconnect-MgGraph -ErrorAction SilentlyContinue
Write-Verbose "Disconnected from Microsoft Graph."
}
catch {
Write-Warning "Could not cleanly disconnect from Microsoft Graph: $_"
}
}
#endregion