⚡ PowerShell & Microsoft Graph Script Library

39 production-tested scripts for Intune, Entra ID, Exchange Online and Windows — detection & remediation pairs, Graph automations and reporting tools. Every script links to the full guide that explains when (and when not) to run it.

9 scripts matching your filters · Browse guides with scripts →

PowerShell 7+Microsoft Graph SDK v2OAuth (M365 SaaS Engine skeleton via PHP endpoint)

Intune Windows PowerShell Script Assignment Reporter (Group Include/Exclusion & Built-in Targets)

Exports a tenant report of Intune Windows PowerShell script assignments, resolving built-in targets (All Devices/All Users) and included/excluded Entra groups for audit-ready change reviews.

📖 Full guide: Intune PowerShell Script Group Exclusions & Built-In Targets
### FILE: README.md
# Intune Windows PowerShell Script Assignment Reporter

## What this repo does
This project inventories Intune **Windows PowerShell Script** assignments using **Microsoft Graph** and produces a CSV report that is suitable for audits and change reviews.

It resolves:
- Built-in include targets: **All Devices** / **All Users** (service release 2611 behavior)
- Included Entra groups and excluded Entra groups (group exclusions)

## Output
A CSV exported to the provided `ExportPath` containing one row per script assignment, with readable group names where possible.

## Components
- `src/Reporter.ps1`: Production-ready PowerShell script logic.
- `index.php`: M365 SaaS Engine-style endpoint skeleton that calls the PowerShell logic.

## Prerequisites
- Admin workstation
- PowerShell 7.x (Windows PowerShell 5.1 supported)
- Microsoft Graph PowerShell SDK v2 modules:
  - `Microsoft.Graph.Authentication`
  - `Microsoft.Graph.DeviceManagement`
  - `Microsoft.Graph.Groups`

## Required Graph Permissions
- `DeviceManagementConfiguration.Read.All`
- `Group.Read.All`

## Run (PowerShell)
```powershell
.
# Example
.\src\Reporter.ps1 -ExportPath .\Intune-WindowsPowerShellScriptAssignments.csv
```

## Run (SaaS)
Use the repository entrypoint `index.php` per your platform conventions.


### FILE: index.php
<?php
/**
 * M365 SaaS Engine endpoint skeleton
 *
 * This file demonstrates how to call Microsoft Graph (via the provided $ms->graphCall helper)
 * and then render UI cards (via render_premium_card).
 *
 * IMPORTANT:
 * - Actual execution of the inventory logic is implemented in PowerShell (src/Reporter.ps1)
 * - This endpoint can be adapted to trigger job execution in your SaaS environment.
 */

// You said: $ms is already initialized.
// You said: $accessToken is in $_SESSION['ms_access_token'].

// Defensive checks
session_start();
$accessToken = $_SESSION['ms_access_token'] ?? null;

if (!$accessToken) {
    http_response_code(401);
    echo json_encode(['error' => 'Missing ms_access_token in session']);
    exit;
}

$title = 'Intune Assignment Reporter';

// Example: quick health check call (count scripts). The full report generation is done in PowerShell.
$endpoint = 'https://graph.microsoft.com/beta/deviceManagement/deviceManagementScripts?$select=id,displayName';

try {
    $resp = $ms->graphCall($endpoint, $accessToken, 'GET', null);
    $count = isset($resp['value']) ? count($resp['value']) : 0;

    echo render_premium_card(
        'Discovered Intune Windows PowerShell scripts',
        (string)$count,
        null,
        'up',
        '📊',
        null
    );

    // In a real SaaS environment, you would enqueue / run src/Reporter.ps1 and return download links.
    // For now, return guidance.
    echo json_encode([
        'ok' => true,
        'scripts_discovered' => $count,
        'next' => 'Run src/Reporter.ps1 to export the full CSV report with include/exclude resolution.'
    ]);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}


### FILE: src/Reporter.ps1
#!/usr/bin/env pwsh
<#
.SYNOPSIS
Inventories Intune Windows PowerShell script assignments, resolving built-in include targets (All Devices/All Users) and group include/exclusion scopes.

.DESCRIPTION
This admin workstation script queries Microsoft Graph for Intune Windows PowerShell scripts (including their assignments), then builds an audit-ready CSV report.

The script understands Intune assignment targets including:
- Built-in include targets: All Devices / All Users (newer behavior aligned to Intune targeting model)
- Included groups (groupAssignmentTarget)
- Excluded groups (exclusionGroupAssignmentTarget)

It outputs a clean report with readable group display names when possible. It also implements throttling retry logic for Graph requests.

.EXAMPLE
.
# Export report to CSV
.\src\Reporter.ps1 -ExportPath .\Intune-WindowsPowerShellScriptAssignments.csv

.NOTES
Author:      Souhaiel Morhag
Company:     MSEndpoint.com
Blog:        https://msendpoint.com
Academy:     https://app.msendpoint.com/academy
LinkedIn:    https://linkedin.com/in/souhaiel-morhag
GitHub:      https://github.com/Msendpoint
License:     MIT
#>

[CmdletBinding(SupportsShouldProcess = $true)]
param(
    [Parameter(Mandatory = $false)]
    [ValidateNotNullOrEmpty()]
    [string]$ExportPath = '.\Intune-WindowsPowerShellScriptAssignments.csv',

    [Parameter(Mandatory = $false)]
    [switch]$IncludeRawAssignments,

    [Parameter(Mandatory = $false)]
    [switch]$PassThru
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

function Write-Log {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]$Message,

        [Parameter(Mandatory = $false)]
        [ValidateSet('INFO','WARN','ERROR','OK')]
        [string]$Level = 'INFO'
    )

    $timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
    switch ($Level) {
        'INFO'  { Write-Host "[$timestamp] [INFO ] $Message" -ForegroundColor Cyan }
        'WARN'  { Write-Host "[$timestamp] [WARN ] $Message" -ForegroundColor Yellow }
        'ERROR' { Write-Host "[$timestamp] [ERROR] $Message" -ForegroundColor Red }
        'OK'     { Write-Host "[$timestamp] [ OK  ] $Message" -ForegroundColor Green }
    }
}

function Test-MgModules {
    [CmdletBinding()]
    param()

    $requiredModules = @(
        'Microsoft.Graph.Authentication',
        'Microsoft.Graph.DeviceManagement',
        'Microsoft.Graph.Groups'
    )

    foreach ($module in $requiredModules) {
        if (-not (Get-Module -ListAvailable -Name $module)) {
            throw "Required module '$module' is not installed. Install-Module $module -Scope CurrentUser"
        }
    }
}

function Connect-GraphIfNeeded {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $false)]
        [string[]]$Scopes = @(
            'DeviceManagementConfiguration.Read.All',
            'Group.Read.All'
        )
    )

    $context = Get-MgContext -ErrorAction SilentlyContinue
    if (-not $context) {
        Write-Log -Message 'Connecting to Microsoft Graph...' -Level INFO
        Connect-MgGraph -Scopes $Scopes -NoWelcome | Out-Null
    }
    else {
        Write-Log -Message "Reusing existing Microsoft Graph context for tenant: $($context.TenantId)" -Level INFO
    }
}

function Invoke-GraphGetWithRetry {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]$Uri,

        [Parameter(Mandatory = $false)]
        [int]$MaxRetryCount = 5
    )

    $attempt = 0
    do {
        try {
            return Invoke-MgGraphRequest -Method GET -Uri $Uri -OutputType PSObject
        }
        catch {
            $attempt++
            $response = $_.Exception.Response
            $statusCode = $null
            $retryAfter = 5

            if ($response) {
                try { $statusCode = [int]$response.StatusCode } catch { $statusCode = $null }

                try {
                    if ($response.Headers -and $response.Headers.Contains('Retry-After')) {
                        $retryAfter = [int]$response.Headers.GetValues('Retry-After')[0]
                    }
                }
                catch {
                    $retryAfter = 5
                }
            }

            if ((($statusCode -eq 429) -or ($statusCode -eq 503)) -and $attempt -lt $MaxRetryCount) {
                Write-Log -Message "Graph throttling/service busy on '$Uri'. Retry $attempt of $MaxRetryCount in $retryAfter second(s)." -Level WARN
                Start-Sleep -Seconds $retryAfter
            }
            else {
                throw
            }
        }
    } while ($attempt -lt $MaxRetryCount)

    throw "Graph request failed after $MaxRetryCount attempts for URI: $Uri"
}

# Cache group display names to reduce Graph calls
$script:GroupNameCache = @{}

function Get-GroupDisplayNameSafe {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]$GroupId
    )

    if ([string]::IsNullOrWhiteSpace($GroupId)) {
        return ''
    }

    if ($script:GroupNameCache.ContainsKey($GroupId)) {
        return $script:GroupNameCache[$GroupId]
    }

    try {
        $group = Get-MgGroup -GroupId $GroupId -Property Id, DisplayName -ErrorAction Stop
        $script:GroupNameCache[$GroupId] = $group.DisplayName
        return $group.DisplayName
    }
    catch {
        Write-Log -Message "Failed to resolve group display name for GroupId '$GroupId'. Using raw ID." -Level WARN
        $script:GroupNameCache[$GroupId] = $GroupId
        return $GroupId
    }
}

function Resolve-AssignmentTarget {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [psobject]$AssignmentTarget
    )

    # The Graph SDK uses an odata.type marker under property '@odata.type'
    $odataType = $AssignmentTarget.'@odata.type'

    switch ($odataType) {
        '#microsoft.graph.allDevicesAssignmentTarget' {
            return [pscustomobject]@{
                TargetType   = 'Include'
                ScopeType    = 'BuiltIn'
                ScopeName    = 'All Devices'
                ScopeId      = 'BuiltIn-AllDevices'
                RawODataType = $odataType
            }
        }
        '#microsoft.graph.allLicensedUsersAssignmentTarget' {
            return [pscustomobject]@{
                TargetType   = 'Include'
                ScopeType    = 'BuiltIn'
                ScopeName    = 'All Users'
                ScopeId      = 'BuiltIn-AllUsers'
                RawODataType = $odataType
            }
        }
        '#microsoft.graph.groupAssignmentTarget' {
            $groupId = $AssignmentTarget.groupId
            return [pscustomobject]@{
                TargetType   = 'Include'
                ScopeType    = 'Group'
                ScopeName    = (Get-GroupDisplayNameSafe -GroupId $groupId)
                ScopeId      = $groupId
                RawODataType = $odataType
            }
        }
        '#microsoft.graph.exclusionGroupAssignmentTarget' {
            $groupId = $AssignmentTarget.groupId
            return [pscustomobject]@{
                TargetType   = 'Exclude'
                ScopeType    = 'Group'
                ScopeName    = (Get-GroupDisplayNameSafe -GroupId $groupId)
                ScopeId      = $groupId
                RawODataType = $odataType
            }
        }
🐙 GitHub
PowerShellMicrosoft GraphPHP

Advanced Driver & BIOS Management

Driver and BIOS management strategies using Intune for HP, Dell & Lenovo devices.

📖 Full guide: Advanced Driver & BIOS Management with Microsoft Intune: HP, Dell & Lenovo Depl…
### FILE: index.php
<?php 

// Import necessary dependencies and initialize Microsoft Graph service

// Function to call Microsoft Graph using the M365 SaaS Engine
function graphCall($endpoint, $accessToken, $method = 'GET', $body = null) {
    global $ms; // Ensure $ms is globally accessible
    return $ms->graphCall($endpoint, $accessToken, $method, $body);
}

// Sample use case to fetch device configuration policies and render UI cards
$accessToken = $_SESSION['ms_access_token'];
$endpoint = '/deviceManagement/deviceConfigurations';
$deviceConfigs = graphCall($endpoint, $accessToken);

foreach ($deviceConfigs as $config) {
    render_premium_card(
        $config['name'], 
        $config['description'],
        null, 
        'up', 
        '📊'
    );
}

?>

### FILE: scripts/DellUpdateAutomation.ps1
<#
.SYNOPSIS
Automates the Dell Command Update process on devices using Dell tools.

.DESCRIPTION
This script utilizes Dell's 'Command | Update' utility to check for and apply pending updates. Designed for environments using Microsoft Intune.

.EXAMPLE
DellUpdateAutomation.ps1 -DellCmdExePath "C:\Program Files\Dell\CommandUpdate\dellcommandupdate.exe"

.NOTES
    Author:      Souhaiel Morhag
    Company:     MSEndpoint.com
    Blog:        https://msendpoint.com
    Academy:     https://app.msendpoint.com/academy
    LinkedIn:    https://linkedin.com/in/souhaiel-morhag
    GitHub:      https://github.com/Msendpoint
    License:     MIT
#>
param (
    [string]$DellCmdExePath = "C:\Program Files\Dell\CommandUpdate\dellcommandupdate.exe"
)

try {
    # Check if Dell Command Update executable exists
    if (Test-Path $DellCmdExePath) {
        # Run scan for pending updates
        & $DellCmdExePath --scan
        if ($LASTEXITCODE -eq 0) {
            Write-Host "Dell scan successful - no updates needed." -ForegroundColor Green
            exit 0
        } else {
            # Run update in silent mode if updates are pending
            Write-Host "Dell scan indicated updates pending." -ForegroundColor Yellow
            & $DellCmdExePath --update --silent
            exit $LASTEXITCODE
        }
    } else {
        Write-Host "Dell Command | Update not found, check installation." -ForegroundColor Red
        exit 1
    }
} catch {
    Write-Host "An error occurred: $_" -ForegroundColor Red
    exit 1
}

# End of Script
🐙 GitHub
PowerShellMicrosoft GraphPHP

Company Portal 24H2 Recovery Kit - AppX Re-registration & Intune Remediation

A production-ready toolkit to detect, remediate, and monitor Company Portal disappearance issues on Windows 24H2 upgrades, combining Proactive Remediation scripts, Graph-based bulk sync, and a SaaS dashboard for tenant-wide visibility.

📖 Full guide: Company Portal Disappearing on Windows 24H2: Root Causes, AppX Re-registration …
### FILE: scripts/Detect-CompanyPortalRegistration.ps1
<#
.SYNOPSIS
    Proactive Remediation DETECTION script for Company Portal AppX registration state on Windows 24H2.

.DESCRIPTION
    Runs as SYSTEM context under Intune Proactive Remediations. Validates whether Microsoft.CompanyPortal
    is both provisioned at the machine level AND registered for the currently logged-on user profile(s).
    24H2 in-place feature updates can leave the package binaries provisioned while dropping the
    per-user AppX registration record, causing Company Portal to vanish from Start Menu/taskbar.

    Exit 0 = Healthy (no remediation needed)
    Exit 1 = Remediation required (triggers paired Remediate script)

.EXAMPLE
    Deploy under Devices > Scripts and remediations > Create.
    Run this script using the logged-on credentials: No (runs as SYSTEM)
    Pair with Remediate-CompanyPortalRegistration.ps1

.NOTES
    Author:      Souhaiel Morhag
    Company:     MSEndpoint.com
    Blog:        https://msendpoint.com
    Academy:     https://app.msendpoint.com/academy
    LinkedIn:    https://linkedin.com/in/souhaiel-morhag
    GitHub:      https://github.com/Msendpoint
    License:     MIT
#>

$ErrorActionPreference = 'Stop'
$logPath = "$env:ProgramData\Microsoft\IntuneManagementExtension\Logs\CP-Detect.log"
$packageName = 'Microsoft.CompanyPortal'

function Write-Log {
    param([string]$Message)
    try {
        $ts = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
        Add-Content -Path $logPath -Value "[$ts] $Message" -ErrorAction SilentlyContinue
    } catch {
        # Logging failures should never break detection logic
    }
}

try {
    Write-Log "=== Detection run started ==="

    # Step 1: Confirm the package is provisioned at the machine level
    $provisioned = Get-AppxProvisionedPackage -Online -ErrorAction SilentlyContinue |
        Where-Object { $_.DisplayName -eq $packageName }

    if (-not $provisioned) {
        Write-Log "FAIL: $packageName not found in provisioned packages. Package itself may be missing - requires full Intune redeploy, not re-registration."
        exit 1
    }

    Write-Log "OK: $packageName found in provisioned packages (Version: $($provisioned.Version))"

    # Step 2: Check per-user registration across all profiles
    $userPkg = Get-AppxPackage -AllUsers -Name $packageName -ErrorAction SilentlyContinue

    if (-not $userPkg) {
        Write-Log "FAIL: No per-user registration found for $packageName across any profile. Remediation required."
        exit 1
    }

    # Step 3: Validate InstallLocation and Status for each registered instance
    $unhealthyInstances = $userPkg | Where-Object {
        [string]::IsNullOrWhiteSpace($_.InstallLocation) -or $_.Status -ne 'Ok'
    }

    if ($unhealthyInstances) {
        foreach ($instance in $unhealthyInstances) {
            Write-Log "FAIL: PackageFullName '$($instance.PackageFullName)' has Status '$($instance.Status)' or empty InstallLocation."
        }
        exit 1
    }

    Write-Log "OK: $packageName is provisioned and registered correctly for all detected user profiles."
    Write-Log "=== Detection run completed: HEALTHY ==="
    exit 0

} catch {
    Write-Log "ERROR: Unhandled exception during detection - $($_.Exception.Message)"
    # Fail safe: treat unexpected errors as remediation-required so the self-healing loop can attempt a fix
    exit 1
}


### FILE: scripts/Remediate-CompanyPortalRegistration.ps1
<#
.SYNOPSIS
    Proactive Remediation REMEDIATION script that re-registers Company Portal's AppX package for all users.

.DESCRIPTION
    Paired with Detect-CompanyPortalRegistration.ps1. Runs as SYSTEM context under Intune Proactive
    Remediations. Locates the provisioned Company Portal AppXManifest.xml on disk and re-registers it
    for every local user profile, closing the per-user registration gap left behind by 24H2 in-place
    feature update servicing.

    If the provisioned package itself is missing (not just the per-user registration), this script
    logs the condition and exits non-zero so the failure surfaces for a full Intune app redeploy instead
    of masking a deeper problem.

.EXAMPLE
    Deploy under Devices > Scripts and remediations > Create.
    Run this script using the logged-on credentials: No (runs as SYSTEM)
    Pair with Detect-CompanyPortalRegistration.ps1

.NOTES
    Author:      Souhaiel Morhag
    Company:     MSEndpoint.com
    Blog:        https://msendpoint.com
    Academy:     https://app.msendpoint.com/academy
    LinkedIn:    https://linkedin.com/in/souhaiel-morhag
    GitHub:      https://github.com/Msendpoint
    License:     MIT
#>

$ErrorActionPreference = 'Stop'
$logPath = "$env:ProgramData\Microsoft\IntuneManagementExtension\Logs\CP-Remediate.log"
$packageName = 'Microsoft.CompanyPortal'

function Write-Log {
    param([string]$Message)
    try {
        $ts = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
        Add-Content -Path $logPath -Value "[$ts] $Message" -ErrorAction SilentlyContinue
    } catch {
        # Logging failures should never break remediation logic
    }
}

try {
    Write-Log "=== Remediation run started ==="

    $provisioned = Get-AppxProvisionedPackage -Online -ErrorAction SilentlyContinue |
        Where-Object { $_.DisplayName -eq $packageName }

    if (-not $provisioned) {
        Write-Log "CRITICAL: $packageName is not provisioned on this device. Re-registration cannot fix a missing package. Escalating to full Intune redeploy."
        exit 1
    }

    $installLocation = $provisioned.InstallLocation
    $manifestPath = Join-Path -Path $installLocation -ChildPath 'AppXManifest.xml'

    if (-not (Test-Path -Path $manifestPath)) {
        Write-Log "CRITICAL: AppXManifest.xml not found at expected path '$manifestPath'. Package binaries may be corrupted or removed. Escalating to full Intune redeploy."
        exit 1
    }
🐙 GitHub
PowerShellMicrosoft GraphPHP

Agent 365 Migration Script Repository

A repository for automating the transition to Agent 365 using PowerShell and Microsoft Graph.

📖 Full guide: Agent Registry API to Agent 365: What to Change Now
### FILE: index.php
<?php

session_start();

// Ensure access token is set
if (!isset($_SESSION['ms_access_token'])) {
    echo 'Access token not found';
    exit;
}

$accessToken = $_SESSION['ms_access_token'];
$endpoint = '/v1.0/agent365/YOUR_AGENT_ID';

try {
    // Fetch data from Microsoft Graph
    $response = $ms->graphCall($endpoint, $accessToken);
    $agentData = json_decode($response, true);

    // Check if data retrieval was successful
    if (!$agentData) {
        throw new Exception('Failed to retrieve agent data.');
    }

    // Render a premium card with the agent details
    render_premium_card(
        'Agent 365 Data',
        json_encode($agentData),
        null,
        'up',
        '📊',
        null
    );

} catch (Exception $e) {
    // Handle errors
    echo 'Error: ' . $e->getMessage();
}

?>

### FILE: scripts/Automation.ps1
<#
.SYNOPSIS
   Retrieves data from Agent 365 using Microsoft Graph API.

.DESCRIPTION
   This script connects to the Microsoft Graph API and retrieves specific agent data using the new Agent 365 endpoints.

.EXAMPLE
   ./Automation.ps1 
#>

try {
    # Connect to Microsoft Graph
    Connect-MgGraph -Scopes "https://graph.microsoft.com/.default"

    # Specify agent identifier
    $agentId = "YOUR_AGENT_ID"

    # API call to fetch the agent data
    $response = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/agent365/$agentId" -Headers @{Authorization = "Bearer $($token)"} -Method GET

    # Output the retrieved data
    Write-Host $response

} catch {
    # Error handling
    Write-Error "An error occurred: $_"
}

<#
.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
#>
PowerShellMicrosoft Graph

Intune Compliance Audit Script

This script audits Intune-managed devices for compliance with security baselines.

📖 Full guide: Understanding Intune's Default Windows Security Baselines
<#
.SYNOPSIS
    Audits Intune-managed devices for compliance with security baselines.
.DESCRIPTION
    This script retrieves a list of devices managed by Intune and checks their compliance status
    by fetching the associated mobile app policy for each device. Ideal for regular compliance checks.
.NOTES
    Author:      Souhaiel Morhag
    Company:     MSEndpoint.com
    Blog:        https://msendpoint.com
    Academy:     https://app.msendpoint.com/academy
    LinkedIn:    https://linkedin.com/in/souhaiel-morhag
    GitHub:      https://github.com/Msendpoint
    License:     MIT
.EXAMPLE
    .\Audit-IntuneCompliance.ps1
#>

[CmdletBinding()]
param ()

try {
    # Retrieve all Intune managed devices
    $devices = Get-IntuneManagedDevice

    # Check compliance for each device
    foreach ($device in $devices) {
        # Fetch mobile app policy for the current device
        $compliancePolicy = Get-IntuneMobileAppPolicy -DeviceId $device.Id
        Write-Output "Device ID: $($device.Id), Compliance Status: $($compliancePolicy.Status)"
    }
} catch {
    Write-Error "An error occurred: $_"
}
🐙 GitHub
PowerShellMicrosoft Intune Proactive RemediationWindows Registry

Outlook Hyperlink Warning Remediation and Trusted Sites Configuration via Intune

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

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

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

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

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

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

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

.NOTES
    Author:      Souhaiel Morhag
    Company:     MSEndpoint.com
    Blog:        https://msendpoint.com
    Academy:     https://app.msendpoint.com/academy
    LinkedIn:    https://linkedin.com/in/souhaiel-morhag
    GitHub:      https://github.com/Msendpoint
    License:     MIT

.EXAMPLE
    # Run the detection script manually to check compliance on a local machine:
    .\Detect-OutlookHyperlinkWarning.ps1

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

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

#region --- Configuration ---

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

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

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

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

#endregion

#region --- Detection Logic ---

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

    $compliance = $true

    Write-Verbose 'Starting compliance detection...'

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

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

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

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

#endregion

#region --- Remediation Logic ---

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

    Write-Verbose 'Starting remediation...'

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

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

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

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

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

#endregion

#region --- Entry Point ---

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

#endregion
🐙 GitHub
PowerShellMicrosoft IntuneProactive RemediationWindows Registry

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

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

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

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

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

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

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

.NOTES
    Author:      Souhaiel Morhag
    Company:     MSEndpoint.com
    Blog:        https://msendpoint.com
    Academy:     https://app.msendpoint.com/academy
    LinkedIn:    https://linkedin.com/in/souhaiel-morhag
    GitHub:      https://github.com/Msendpoint
    License:     MIT

.EXAMPLE
    # Run detection locally to check current Office default format settings:
    .\Detect-OfficeDefaultFormat.ps1

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

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

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

[CmdletBinding()]
param()

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

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

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

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

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

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

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

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

#endregion


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

<#
[CmdletBinding()]
param()

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

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

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

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

#endregion
🐙 GitHub
PowerShellWindows RegistryMicrosoft Intune Win32 App Detection

Intune Win32 App Detection Rule Validator

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

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

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

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

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

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

.NOTES
    Author:      Souhaiel Morhag
    Company:     MSEndpoint.com
    Blog:        https://msendpoint.com
    Academy:     https://app.msendpoint.com/academy
    LinkedIn:    https://linkedin.com/in/souhaiel-morhag
    GitHub:      https://github.com/Msendpoint
    License:     MIT

.EXAMPLE
    # Run locally to test detection for an app with a known GUID and minimum version:
    .\Invoke-Win32AppDetection.ps1 -AppGuid '{12345678-1234-1234-1234-123456789012}' -MinimumVersion '1.5.3.2501222'

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

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

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

#region --- Configuration ---

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

#endregion

#region --- Helper Functions ---

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

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

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

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

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

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

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

#endregion

#region --- Main Detection Logic ---

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

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

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

    Write-Verbose "Installed version detected: $installedVersion"

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

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

#endregion
🐙 GitHub
PowerShellMicrosoft IntuneProactive Remediations

Intune Secure Boot and OS Compliance Detection Script

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

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

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

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

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

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

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

.NOTES
    Author:      Souhaiel Morhag
    Company:     MSEndpoint.com
    Blog:        https://msendpoint.com
    Academy:     https://app.msendpoint.com/academy
    LinkedIn:    https://linkedin.com/in/souhaiel-morhag
    GitHub:      https://github.com/Msendpoint
    License:     MIT

.EXAMPLE
    # Run locally on a single device to verify output before deploying via Intune:
    .\Detect-SecureBootCompliance.ps1

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

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

[CmdletBinding()]
param()

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

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

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

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

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

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

if ($isSecureBootCompliant -and $isBuildCompliant) {
    # Device meets all compliance criteria — no remediation needed
    exit 0
} else {
    # Device is non-compliant — Intune will trigger the paired remediation script
    exit 1
}
🐙 GitHub
📡 New scripts every week

Get new remediation scripts and the Weekly TV digest in your inbox.

Subscribe free →

⚠️ Always review and test scripts in a pilot group before production use. Scripts are provided as-is under the terms of each GitHub repository.