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.
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.
?>
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
}
### FILE: index.php
<?php
// Ensure user is authenticated and has a valid access token
if (!isset($_SESSION['ms_access_token'])) {
echo 'Access token is missing.';
exit;
}
// Fetch device compliance policies from Microsoft Graph
function fetchDeviceCompliancePolicies($ms, $accessToken) {
try {
$endpoint = 'https://graph.microsoft.com/v1.0/deviceManagement/deviceCompliancePolicies';
$response = $ms->graphCall($endpoint, $accessToken, 'GET');
return $response;
} catch (Exception $e) {
echo 'Error fetching compliance policies: ' . $e->getMessage();
return null;
}
}
// Retrieve the list
$compliancePolicies = fetchDeviceCompliancePolicies($ms, $_SESSION['ms_access_token']);
// Render premium card with fetched data
echo render_premium_card('Device Compliance Policies', json_encode($compliancePolicies));
?>
### FILE: scripts/Automation.ps1
<#
.SYNOPSIS
Retrieves and exports all devices under Intune management.
.DESCRIPTION
This script connects to Microsoft Graph using the MgGraph module, retrieves all managed devices, and exports the list to a CSV file.
.EXAMPLE
.\Automation.ps1
.NOTES
Author: Souhaiel Morhag
Company: MSEndpoint.com
Blog: https://msendpoint.com
Academy: https://app.msendpoint.com/academy
LinkedIn: https://linkedin.com/in/souhaiel-morhag
GitHub: https://github.com/Msendpoint
License: MIT
#>
try {
# Connect to Microsoft Graph
Connect-MgGraph -Scopes "DeviceManagementConfiguration.Read.All"
# Retrieve the list of managed devices
$devices = Get-MgDeviceManagementManagedDevice
# Export the devices to a CSV file
$devices | Export-Csv -Path "intune_devices.csv" -NoTypeInformation
Write-Output "Device list exported successfully to intune_devices.csv."
} catch {
Write-Error "Failed to export device list: $_.Exception.Message"
}
PowerShell
Automate Enrollment of Apple TV Devices
Automate the enrollment of corporate-owned Apple TV devices into Microsoft Intune using Apple's ADE.
[{"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
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
}
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 ---