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