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.
PowerShell scripts to configure a resilient Azure VPN Gateway connection to Azure Vianet using BGP and custom IPSec policies for dynamic routing and improved stability.
### FILE: scripts/Set-AzureVianetVpnConnection.ps1
<#
.SYNOPSIS
Configures a resilient Azure VPN Gateway connection to Azure Vianet using BGP and custom IPSec policies.
.DESCRIPTION
This script automates the setup and configuration of a route-based Azure VPN Gateway,
a Local Network Gateway representing the Azure Vianet side, and an IPsec connection
between them. It enablesBGP enabled. It handles creation or update of the Azure Virtual Network Gateway, the Local Network Gateway representing the Vianet peer, and the IPsec connection between them. It specifically configures advanced IPsec parameters and enables BGP for dynamic routing, which is crucial for maintaining stable connectivity between Azure Global and Azure Vianet environments.
.EXAMPLE
Set-VianetAzureVpnConnection `
-ResourceGroupName "Contoso-US-Network-RG" `
-Location "EastUS" `
-VNetName "Contoso-
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')
})
}
[{"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"}]
<#
.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: $_"
}
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.
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.
Validates and generates version-aware registry detection logic for Intune Win32 apps to prevent endless reinstall loops caused by auto-updating software.
<#
.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
Monitor Sensitivity Label Policy Sync Status in Microsoft Purview
Connects to Security & Compliance PowerShell and reports the distribution/sync status of all sensitivity label publishing policies, highlighting any that are not yet fully propagated.
<#
.SYNOPSIS
Monitors and reports the sync/distribution status of all sensitivity label publishing policies in Microsoft Purview.
.DESCRIPTION
This script connects to the Security & Compliance PowerShell endpoint using the
ExchangeOnlineManagement module and retrieves all sensitivity label publishing policies
along with their DistributionStatus property.
It is designed to help Microsoft Purview / Information Protection administrators:
- Confirm that policy changes have fully propagated across Microsoft 365 infrastructure.
- Identify policies that are still in a Pending or failed state after a change.
- Automate post-change validation as part of a change management or compliance workflow.
The DistributionStatus field returns one of the following values:
- Success : Policy is fully distributed and live for all targeted users.
- Pending : Policy change is queued or propagation has not yet completed.
- Failed : An error occurred during distribution; immediate investigation recommended.
This script is especially useful in regulated environments where you need to confirm
that a sensitivity label policy is in force before closing a change management ticket
or meeting a compliance deadline.
.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
.PARAMETER UserPrincipalName
The UPN of the admin account used to authenticate to Security & Compliance PowerShell.
Must have Compliance Administrator or Global Administrator rights.
.PARAMETER ShowAllPolicies
Switch parameter. When specified, the script outputs ALL policies regardless of status.
By default, only policies that are NOT in a 'Success' state are highlighted.
.EXAMPLE
# Run the script and show only non-successful (pending/failed) policies:
.\Get-LabelPolicySyncStatus.ps1 -UserPrincipalName admin@yourtenant.onmicrosoft.com
.EXAMPLE
# Run the script and show ALL policies including successfully synced ones:
.\Get-LabelPolicySyncStatus.ps1 -UserPrincipalName admin@yourtenant.onmicrosoft.com -ShowAllPolicies
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, HelpMessage = 'Enter the UPN of the compliance/global admin account.')]
[ValidateNotNullOrEmpty()]
[string]$UserPrincipalName,
[Parameter(Mandatory = $false, HelpMessage = 'Show all policies, including successfully synced ones.')]
[switch]$ShowAllPolicies
)
#region --- Module Check and Installation ---
Write-Host "[INFO] Checking for ExchangeOnlineManagement module..." -ForegroundColor Cyan
try {
if (-not (Get-Module -ListAvailable -Name ExchangeOnlineManagement)) {
Write-Host "[INFO] ExchangeOnlineManagement module not found. Installing for current user..." -ForegroundColor Yellow
Install-Module -Name ExchangeOnlineManagement -Force -Scope CurrentUser -ErrorAction Stop
Write-Host "[INFO] Module installed successfully." -ForegroundColor Green
} else {
Write-Host "[INFO] ExchangeOnlineManagement module is already installed." -ForegroundColor Green
}
} catch {
Write-Error "[ERROR] Failed to install ExchangeOnlineManagement module. Please install it manually. Details: $_"
exit 1
}
#endregion
#region --- Connect to Security & Compliance PowerShell ---
Write-Host "[INFO] Connecting to Security & Compliance PowerShell as '$UserPrincipalName'..." -ForegroundColor Cyan
try {
Connect-IPPSSession -UserPrincipalName $UserPrincipalName -ErrorAction Stop
Write-Host "[INFO] Successfully connected to Security & Compliance PowerShell." -ForegroundColor Green
} catch {
Write-Error "[ERROR] Failed to connect to Security & Compliance PowerShell. Details: $_"
exit 1
}
#endregion
#region --- Retrieve Label Policies ---
Write-Host "[INFO] Retrieving all sensitivity label publishing policies..." -ForegroundColor Cyan
try {
$allPolicies = Get-LabelPolicy -ErrorAction Stop | Select-Object -Property Name, Guid, DistributionStatus, LastModifiedTime, WhenCreated
} catch {
Write-Error "[ERROR] Failed to retrieve label policies. Ensure the account has the required permissions. Details: $_"
exit 1
}
if (-not $allPolicies) {
Write-Warning "[WARN] No sensitivity label policies were found in this tenant."
exit 0
}
Write-Host "[INFO] Total policies retrieved: $($allPolicies.Count)" -ForegroundColor Cyan
#endregion
#region --- Display All Policies (if requested) ---
if ($ShowAllPolicies) {
Write-Host "`n=== ALL Sensitivity Label Policies ===" -ForegroundColor White
$allPolicies | Format-Table -AutoSize
}
#endregion
#region --- Identify Non-Successful Policies ---
Write-Host "`n[INFO] Checking for policies that are NOT in a 'Success' state..." -ForegroundColor Cyan
# Filter for any policy that has not fully synced
$pendingPolicies = $allPolicies | Where-Object { $_.DistributionStatus -ne 'Success' }
if ($pendingPolicies.Count -eq 0) {
Write-Host "[SUCCESS] All sensitivity label policies have a DistributionStatus of 'Success'. No action required." -ForegroundColor Green
} else {
Write-Warning "[WARN] The following $($pendingPolicies.Count) policy/policies have NOT completed distribution:"
$pendingPolicies | Format-Table -AutoSize
# Separate and call out any explicitly failed policies for immediate attention
$failedPolicies = $pendingPolicies | Where-Object { $_.DistributionStatus -eq 'Failed' }
if ($failedPolicies.Count -gt 0) {
Write-Host "`n[CRITICAL] The following policies have a 'Failed' distribution status and require immediate investigation:" -ForegroundColor Red
$failedPolicies | Format-Table -AutoSize
}
}
#endregion
#region --- Summary Report ---
Write-Host "`n=== Sensitivity Label Policy Sync Status Summary ===" -ForegroundColor White
Write-Host "Total Policies : $($allPolicies.Count)"
Write-Host "Successful : $(($allPolicies | Where-Object { $_.DistributionStatus -eq 'Success' }).Count)" -ForegroundColor Green
Write-Host "Pending : $(($allPolicies | Where-Object { $_.DistributionStatus -eq 'Pending' }).Count)" -ForegroundColor Yellow
Write-Host "Failed : $(($allPolicies | Where-Object { $_.DistributionStatus -eq 'Failed' }).Count)" -ForegroundColor Red
Write-Host "Other/Unknown : $(($allPolicies | Where-Object { $_.DistributionStatus -notin @('Success','Pending','Failed') }).Count)" -ForegroundColor Gray
Write-Host "===================================================`n" -ForegroundColor White
#endregion
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 ---
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
}
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
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.
<#
.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 ---