⚡ 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.

8 scripts matching your filters · Browse guides with scripts →

PowerShellMicrosoft GraphIntune

Intune Device Compliance & Health Auditor

Automated PowerShell script utilizing Microsoft Graph v2 SDK to audit endpoint compliance states, hardware metrics, and synchronization health across Microsoft Intune fleets.

📖 Full guide: Successfully Transitioning from MS-102 to MD-102: Intune Focused Strategies
<#
.SYNOPSIS
   Automated Intune Device Compliance and Health Auditor.

.DESCRIPTION
   Audits Microsoft Intune enrolled endpoints using Microsoft Graph PowerShell SDK v2.
   Checks compliance states, operating system versions, and sync intervals to enforce Zero Trust hygiene.

.PARAMETER ComplianceFilter
   Filter by compliance status: All, Compliant, Noncompliant, or InGracePeriod. Default: Noncompliant.

.PARAMETER Top
   Maximum number of records to retrieve. Default: 100.

.EXAMPLE
   .\Test-IntuneDeviceReadiness.ps1 -ComplianceFilter Noncompliant

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

[CmdletBinding()]
param(
    [Parameter(Mandatory = $false)]
    [ValidateSet('All', 'Compliant', 'Noncompliant', 'InGracePeriod')]
    [string]$ComplianceFilter = 'Noncompliant',

    [Parameter(Mandatory = $false)]
    [int]$Top = 100
)

Begin {
    Write-Host "[INIT] Verifying Microsoft Graph Authentication context..." -ForegroundColor Cyan
    try {
        $context = Get-MgContext -ErrorAction Stop
        if (-not $context) {
            throw "No active Graph session detected. Run 'Connect-MgGraph -Scopes DeviceManagementManagedDevices.Read.All'"
        }
        Write-Host "  -> Connected to Tenant ID: $($context.TenantId)" -ForegroundColor Green
    }
    catch {
        Write-Error "Authentication failure: $_"
        exit 1
    }
}

Process {
    Write-Host "[QUERY] Fetching managed endpoints (Filter: $ComplianceFilter)..." -ForegroundColor Cyan
    
    $filterExpression = $null
    if ($ComplianceFilter -ne 'All') {
        $filterExpression = "complianceState eq '$($ComplianceFilter.ToLower())'"
    }

    try {
        $params = @{
            Property = @(
                'id', 'deviceName', 'operatingSystem', 'osVersion', 
                'complianceState', 'userPrincipalName', 'lastSyncDateTime',
                'enrolledDateTime', 'serialNumber', 'manufacturer', 'model'
            )
            Top = $Top
        }

        if ($filterExpression) {
            $params['Filter'] = $filterExpression
        }

        $devices = Get-MgDeviceManagementManagedDevice @params -ErrorAction Stop

        if (-not $devices -or $devices.Count -eq 0) {
            Write-Host "  -> No devices matched criteria '$ComplianceFilter'." -ForegroundColor Yellow
            return
        }

        Write-Host "  -> Retrieved $($devices.Count) device records. Analyzing compliance telemetry..." -ForegroundColor Green

        $report = foreach ($dev in $devices) {
            [PSCustomObject]@{
                DeviceId         = $dev.Id
                DeviceName       = $dev.DeviceName
                PrimaryUser      = $dev.UserPrincipalName
                OS               = "$($dev.OperatingSystem) ($($dev.OsVersion))"
                Hardware         = "$($dev.Manufacturer) $($dev.Model)"
                ComplianceState  = $dev.ComplianceState
                LastSyncUTC      = $dev.LastSyncDateTime
                DaysSinceSync    = if ($dev.LastSyncDateTime) { [math]::Round(((Get-Date) - $dev.LastSyncDateTime).TotalDays, 1) } else { 'N/A' }
            }
        }

        $report | Format-Table -AutoSize
        return $report
    }
    catch {
        Write-Error "Failed to retrieve Intune device inventory: $_"
        exit 1
    }
}
🐙 GitHub
PowerShellMicrosoft GraphExchange Online ManagementPHP

Exchange Online EWS Retirement Toolkit - Discovery, Whitelist Containment & Phased Cutover

A PowerShell and M365 SaaS toolkit to discover EWS-dependent applications, correlate audit logs against Entra ID app registrations, manage EwsAllowedAppIDs containment, and execute a phased mailbox-level EWS cutover ahead of the October 2026 retirement.

📖 Full guide: Exchange Online EWS Retirement 2026: EwsEnabled & EwsAllowedAppIDs Enforcement …
### FILE: README.md
# Exchange Online EWS Retirement Toolkit

## Overview
October 2026 marks a hard authentication cutoff for EWS in Exchange Online. This toolkit implements the full discovery-to-remediation playbook:

1. **Baseline** — audit org-wide and per-mailbox EWS configuration.
2. **Discovery** — pull 12 months of `EwsConnect` Unified Audit Log events.
3. **Correlation** — resolve `ClientAppId` GUIDs to Entra ID app registrations, owners, and secret/cert expiration.
4. **Containment** — manage `EwsAllowedAppIDs` as a time-boxed whitelist with remediation tickets.
5. **Phased Cutover** — flip mailbox-level `EwsEnabled` by cohort, validate, then lock down org-wide.
6. **Dashboard** — an M365 SaaS Engine dashboard (PHP) surfacing discovery metrics via Microsoft Graph.

## Structure
```
scripts/
  1-Get-EwsBaselineConfig.ps1
  2-Export-EwsConnectAuditLogs.ps1
  3-Resolve-EwsClientAppIds.ps1
  4-Manage-EwsAllowedAppIDsWhitelist.ps1
  5-Set-EwsMailboxCohortCutover.ps1
  6-Invoke-EwsOrgWideLockdown.ps1
src/
  index.php
  includes/graph_helpers.php
```

## Required Scopes / Roles
- Entra ID App/Delegated: `Exchange.ManageAsApp`, `AuditLog.Read.All`, `Application.Read.All`
- Exchange Online Role: `View-Only Organization Management` (discovery) / `Organization Management` (remediation)

## Author
**Souhaiel Morhag** — [MSEndpoint.com](https://msendpoint.com) | [Academy](https://app.msendpoint.com/academy) | [LinkedIn](https://linkedin.com/in/souhaiel-morhag) | [GitHub](https://github.com/Msendpoint)


### FILE: scripts/1-Get-EwsBaselineConfig.ps1
<#
.SYNOPSIS
    Baselines the current Exchange Online EWS configuration at the org-wide and per-mailbox level.

.DESCRIPTION
    Connects to Exchange Online and reports on the org-wide EwsEnabled default (Get-OrganizationConfig),
    the current EwsAllowedAppIDs whitelist, and a per-mailbox export of EwsEnabled overrides via
    Get-CASMailbox. Use this as the mandatory first step of the EWS retirement playbook before
    making any containment or cutover changes. Exports results to CSV for audit trail purposes.

.EXAMPLE
    .\1-Get-EwsBaselineConfig.ps1 -OutputPath "C:\EwsAudit\Baseline"

    Connects to Exchange Online, pulls org-wide and per-mailbox EWS settings, and writes
    OrgConfig-Baseline.csv and MailboxEws-Baseline.csv to the specified folder.

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

[CmdletBinding()]
param(
    [Parameter(Mandatory = $false)]
    [string]$OutputPath = ".\EwsBaseline"
)

begin {
    if (-not (Test-Path -Path $OutputPath)) {
        New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null
    }

    if (-not (Get-Module -Name ExchangeOnlineManagement -ListAvailable)) {
        throw "ExchangeOnlineManagement module is required. Install it via: Install-Module ExchangeOnlineManagement"
    }
}

process {
    try {
        Write-Host "Connecting to Exchange Online..." -ForegroundColor Cyan
        Connect-ExchangeOnline -ShowBanner:$false -ErrorAction Stop

        Write-Host "Retrieving org-wide EWS configuration..." -ForegroundColor Cyan
        $orgConfig = Get-OrganizationConfig -ErrorAction Stop |
            Select-Object Identity, EwsEnabled, EwsAllowedAppIDs, EwsApplicationAccessPolicy

        $orgConfigPath = Join-Path -Path $OutputPath -ChildPath "OrgConfig-Baseline.csv"
        $orgConfig | Export-Csv -Path $orgConfigPath -NoTypeInformation -Encoding UTF8
        Write-Host "Org-wide config exported to: $orgConfigPath" -ForegroundColor Green

        if ($orgConfig.EwsEnabled -eq $true -and [string]::IsNullOrEmpty($orgConfig.EwsAllowedAppIDs)) {
            Write-Warning "Org-wide EwsEnabled = TRUE with NO EwsAllowedAppIDs whitelist. Every registered app with a valid OAuth token can currently reach every mailbox via EWS."
        }

        Write-Host "Retrieving per-mailbox EWS overrides (this may take a while at scale)..." -ForegroundColor Cyan
        $mailboxes = Get-CASMailbox -ResultSize Unlimited -ErrorAction Stop |
            Select-Object Identity, PrimarySmtpAddress, EwsEnabled, EwsAllowedAppIDs

        $mailboxPath = Join-Path -Path $OutputPath -ChildPath "MailboxEws-Baseline.csv"
        $mailboxes | Export-Csv -Path $mailboxPath -NoTypeInformation -Encoding UTF8
        Write-Host "Per-mailbox EWS baseline exported to: $mailboxPath" -ForegroundColor Green

        $summary = [PSCustomObject]@{
            TotalMailboxes            = $mailboxes.Count
            MailboxesWithEwsExplicitlyDisabled = ($mailboxes | Where-Object { $_.EwsEnabled -eq $false }).Count
            MailboxesWithNoOverride   = ($mailboxes | Where-Object { $null -eq $_.EwsEnabled }).Count
            OrgWideEwsEnabled         = $orgConfig.EwsEnabled
            OrgWideWhitelistCount     = ($orgConfig.EwsAllowedAppIDs | Measure-Object).Count
        }

        Write-Host "`n--- Baseline Summary ---" -ForegroundColor Yellow
        $summary | Format-List
    }
    catch {
        Write-Error "Baseline collection failed: $($_.Exception.Message)"
        throw
    }
    finally {
        Disconnect-ExchangeOnline -Confirm:$false -ErrorAction SilentlyContinue
    }
}
🐙 GitHub
PowerShellMicrosoft GraphExchange Online ManagementPHP

Copilot Pages MC1466760 - UX Change Readiness Toolkit

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).

📖 Full guide: Microsoft Copilot Pages: Streamlined Access via Slash Commands & Library Tab—Se…
### 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
}
🐙 GitHub
PowerShellMicrosoft Teams PowerShell ModuleMicrosoft GraphPHP

Teams Copilot Chat Governance Toolkit for GCC, GCC High & DoD

PowerShell audit tooling and a Microsoft 365 SaaS Engine dashboard for tracking and controlling Teams Copilot Chat rollout compliance across US Government cloud instances (GCC, GCC High, DoD).

📖 Full guide: Microsoft Teams Copilot Chat for GCC, GCC High & DoD: Government Cloud Rollout,…
### FILE: scripts/Audit-CopilotChatEnablement.ps1
<# 
.SYNOPSIS
    Cross-cloud audit of Microsoft Teams Copilot Chat enablement signals across GCC, GCC High, and DoD tenants.

.DESCRIPTION
    This script connects to a specified US Government Community Cloud instance (GCC, GCC High, or DoD)
    using the MicrosoftTeams PowerShell module and enumerates all Teams Messaging Policies and Meeting
    Policies to determine the current enablement state of Copilot Chat surfaces (1:1/Group Chat, Channels,
    Calls, Meetings).

    Because Teams PowerShell sessions are cloud-instance-specific and credentials do not roam across
    sovereign cloud boundaries, this script must be run once per cloud instance connection by an admin
    holding the appropriate role in that tenant.

    The report flags policies where transcription-dependent Copilot features (Calls/Meetings recap) may
    be blocked due to 'AllowTranscription' being disabled at the tenant or policy level -- a common
    inherited default in DoD-adjacent CMMC/NIST 800-171 hardening baselines.

    IMPORTANT: Property names such as AllowCopilotChat and AllowChannelSummary reflect the schema at
    time of writing (Sep 2026) and are subject to change post-GA. Always validate against:
        Get-CsTeamsMessagingPolicy | Get-Member -MemberType Property
    before relying on this script's output in a compliance report.

.EXAMPLE
    .\Audit-CopilotChatEnablement.ps1 -CloudInstance GCCHigh -TenantAdminUPN admin@contoso.us

    Connects to the GCC High cloud instance as admin@contoso.us and exports a CSV audit report to the
    default C:\Reports path.

.EXAMPLE
    .\Audit-CopilotChatEnablement.ps1 -CloudInstance DoD -TenantAdminUPN admin@contoso.mil -ReportPath 'D:\Audits\dod_copilot_audit.csv'

    Connects to the DoD cloud instance and writes the report to a custom path.

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

[CmdletBinding()]
param(
    [Parameter(Mandatory = $true)]
    [ValidateSet('GCC','GCCHigh','DoD')]
    [string]$CloudInstance,

    [Parameter(Mandatory = $true)]
    [string]$TenantAdminUPN,

    [Parameter(Mandatory = $false)]
    [string]$ReportPath = "C:\Reports\CopilotChat_Audit_$(Get-Date -Format 'yyyyMMdd_HHmm').csv"
)

$ErrorActionPreference = 'Stop'
$results = [System.Collections.Generic.List[Object]]::new()

# Map cloud instance to the correct Teams PowerShell admin endpoint (reference only —
# actual connection is handled via TeamsEnvironmentName below)
$cloudEndpointMap = @{
    'GCC'     = 'https://admin.teams.microsoft.com'
    'GCCHigh' = 'https://admin.teams.microsoft.us'
    'DoD'     = 'https://admin.teams.microsoft.us'
}

try {

    # Ensure the report directory exists before we attempt to write to it
    $reportDir = Split-Path -Path $ReportPath -Parent
    if ($reportDir -and -not (Test-Path -Path $reportDir)) {
        New-Item -Path $reportDir -ItemType Directory -Force | Out-Null
    }

    Write-Host "[+] Connecting to Teams PowerShell — Cloud Instance: $CloudInstance ($($cloudEndpointMap[$CloudInstance]))" -ForegroundColor Cyan

    $connectParams = @{
        AccountId = $TenantAdminUPN
    }

    # GCC uses the standard commercial cloud endpoint implicitly; GCC High and DoD require
    # explicit environment targeting so the module authenticates against the correct boundary
    switch ($CloudInstance) {
        'GCCHigh' { $connectParams['TeamsEnvironmentName'] = 'TeamsGCCH' }
        'DoD'     { $connectParams['TeamsEnvironmentName'] = 'TeamsDOD' }
    }

    Connect-MicrosoftTeams @connectParams

    Write-Host "[+] Connected. Enumerating messaging and meeting policies..." -ForegroundColor Cyan

    # Pull ALL messaging policies — Copilot Chat surface toggle lives here in current builds
    $messagingPolicies = Get-CsTeamsMessagingPolicy

    foreach ($policy in $messagingPolicies) {

        # Property names below reflect current (Sep 2026) schema; validate against
        # Get-CsTeamsMessagingPolicy | Get-Member if Microsoft renames properties post-GA
        $copilotChatEnabled    = $policy.AllowCopilotChat -as [bool]
        $channelSummaryEnabled = $policy.AllowChannelSummary -as [bool]

        $results.Add([PSCustomObject]@{
            CloudInstance       = $CloudInstance
            RecordType          = 'MessagingPolicy'
            PolicyName          = $policy.Identity
            AllowCopilotChat    = $copilotChatEnabled
            AllowChannelSummary = $channelSummaryEnabled
            IsGlobalPolicy      = ($policy.Identity -eq 'Global')
            AllowTranscription  = $null
            AllowCloudRecording = $null
            CopilotDependencyMet = $null
            AuditTimestamp      = (Get-Date).ToString('o')
        })
    }

    # Cross-reference meeting policies for the transcription dependency gate — Calls and
    # Meetings Copilot recap features require AllowTranscription to be $true
    $meetingPolicies = Get-CsTeamsMeetingPolicy

    foreach ($mp in $meetingPolicies) {
        $results.Add([PSCustomObject]@{
            CloudInstance        = $CloudInstance
            RecordType           = 'MeetingPolicy'
            PolicyName           = $mp.Identity
            AllowCopilotChat     = $null
            AllowChannelSummary  = $null
            IsGlobalPolicy       = ($mp.Identity -eq 'Global')
            AllowTranscription   = $mp.AllowTranscription -as [bool]
            AllowCloudRecording  = $mp.AllowCloudRecording -as [bool]
            CopilotDependencyMet = ($mp.AllowTranscription -eq $true)
            AuditTimestamp       = (Get-Date).ToString('o')
        })
    }
🐙 GitHub
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
PowerShellExchangeOnlineManagementSecurity & Compliance PowerShell (IPPS)Microsoft Purview

Monitor Sensitivity Label Policy Sync Status in Microsoft Purview

Connects to Security & Compliance PowerShell and reports the distribution/sync status of all sensitivity label publishing policies, highlighting any that are not yet fully propagated.

📖 Full guide: Microsoft Purview: How to Monitor Sensitivity Label Policy Sync Status in the P…
<#
.SYNOPSIS
    Monitors and reports the sync/distribution status of all sensitivity label publishing policies in Microsoft Purview.

.DESCRIPTION
    This script connects to the Security & Compliance PowerShell endpoint using the
    ExchangeOnlineManagement module and retrieves all sensitivity label publishing policies
    along with their DistributionStatus property.

    It is designed to help Microsoft Purview / Information Protection administrators:
      - Confirm that policy changes have fully propagated across Microsoft 365 infrastructure.
      - Identify policies that are still in a Pending or failed state after a change.
      - Automate post-change validation as part of a change management or compliance workflow.

    The DistributionStatus field returns one of the following values:
      - Success   : Policy is fully distributed and live for all targeted users.
      - Pending   : Policy change is queued or propagation has not yet completed.
      - Failed    : An error occurred during distribution; immediate investigation recommended.

    This script is especially useful in regulated environments where you need to confirm
    that a sensitivity label policy is in force before closing a change management ticket
    or meeting a compliance deadline.

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

.PARAMETER UserPrincipalName
    The UPN of the admin account used to authenticate to Security & Compliance PowerShell.
    Must have Compliance Administrator or Global Administrator rights.

.PARAMETER ShowAllPolicies
    Switch parameter. When specified, the script outputs ALL policies regardless of status.
    By default, only policies that are NOT in a 'Success' state are highlighted.

.EXAMPLE
    # Run the script and show only non-successful (pending/failed) policies:
    .\Get-LabelPolicySyncStatus.ps1 -UserPrincipalName admin@yourtenant.onmicrosoft.com

.EXAMPLE
    # Run the script and show ALL policies including successfully synced ones:
    .\Get-LabelPolicySyncStatus.ps1 -UserPrincipalName admin@yourtenant.onmicrosoft.com -ShowAllPolicies
#>

[CmdletBinding()]
param (
    [Parameter(Mandatory = $true, HelpMessage = 'Enter the UPN of the compliance/global admin account.')]
    [ValidateNotNullOrEmpty()]
    [string]$UserPrincipalName,

    [Parameter(Mandatory = $false, HelpMessage = 'Show all policies, including successfully synced ones.')]
    [switch]$ShowAllPolicies
)

#region --- Module Check and Installation ---
Write-Host "[INFO] Checking for ExchangeOnlineManagement module..." -ForegroundColor Cyan

try {
    if (-not (Get-Module -ListAvailable -Name ExchangeOnlineManagement)) {
        Write-Host "[INFO] ExchangeOnlineManagement module not found. Installing for current user..." -ForegroundColor Yellow
        Install-Module -Name ExchangeOnlineManagement -Force -Scope CurrentUser -ErrorAction Stop
        Write-Host "[INFO] Module installed successfully." -ForegroundColor Green
    } else {
        Write-Host "[INFO] ExchangeOnlineManagement module is already installed." -ForegroundColor Green
    }
} catch {
    Write-Error "[ERROR] Failed to install ExchangeOnlineManagement module. Please install it manually. Details: $_"
    exit 1
}
#endregion

#region --- Connect to Security & Compliance PowerShell ---
Write-Host "[INFO] Connecting to Security & Compliance PowerShell as '$UserPrincipalName'..." -ForegroundColor Cyan

try {
    Connect-IPPSSession -UserPrincipalName $UserPrincipalName -ErrorAction Stop
    Write-Host "[INFO] Successfully connected to Security & Compliance PowerShell." -ForegroundColor Green
} catch {
    Write-Error "[ERROR] Failed to connect to Security & Compliance PowerShell. Details: $_"
    exit 1
}
#endregion

#region --- Retrieve Label Policies ---
Write-Host "[INFO] Retrieving all sensitivity label publishing policies..." -ForegroundColor Cyan

try {
    $allPolicies = Get-LabelPolicy -ErrorAction Stop | Select-Object -Property Name, Guid, DistributionStatus, LastModifiedTime, WhenCreated
} catch {
    Write-Error "[ERROR] Failed to retrieve label policies. Ensure the account has the required permissions. Details: $_"
    exit 1
}

if (-not $allPolicies) {
    Write-Warning "[WARN] No sensitivity label policies were found in this tenant."
    exit 0
}

Write-Host "[INFO] Total policies retrieved: $($allPolicies.Count)" -ForegroundColor Cyan
#endregion

#region --- Display All Policies (if requested) ---
if ($ShowAllPolicies) {
    Write-Host "`n=== ALL Sensitivity Label Policies ==="  -ForegroundColor White
    $allPolicies | Format-Table -AutoSize
}
#endregion

#region --- Identify Non-Successful Policies ---
Write-Host "`n[INFO] Checking for policies that are NOT in a 'Success' state..." -ForegroundColor Cyan

# Filter for any policy that has not fully synced
$pendingPolicies = $allPolicies | Where-Object { $_.DistributionStatus -ne 'Success' }

if ($pendingPolicies.Count -eq 0) {
    Write-Host "[SUCCESS] All sensitivity label policies have a DistributionStatus of 'Success'. No action required." -ForegroundColor Green
} else {
    Write-Warning "[WARN] The following $($pendingPolicies.Count) policy/policies have NOT completed distribution:"
    $pendingPolicies | Format-Table -AutoSize

    # Separate and call out any explicitly failed policies for immediate attention
    $failedPolicies = $pendingPolicies | Where-Object { $_.DistributionStatus -eq 'Failed' }
    if ($failedPolicies.Count -gt 0) {
        Write-Host "`n[CRITICAL] The following policies have a 'Failed' distribution status and require immediate investigation:" -ForegroundColor Red
        $failedPolicies | Format-Table -AutoSize
    }
}
#endregion

#region --- Summary Report ---
Write-Host "`n=== Sensitivity Label Policy Sync Status Summary ===" -ForegroundColor White
Write-Host "Total Policies      : $($allPolicies.Count)"
Write-Host "Successful          : $(($allPolicies | Where-Object { $_.DistributionStatus -eq 'Success' }).Count)" -ForegroundColor Green
Write-Host "Pending             : $(($allPolicies | Where-Object { $_.DistributionStatus -eq 'Pending' }).Count)" -ForegroundColor Yellow
Write-Host "Failed              : $(($allPolicies | Where-Object { $_.DistributionStatus -eq 'Failed' }).Count)" -ForegroundColor Red
Write-Host "Other/Unknown       : $(($allPolicies | Where-Object { $_.DistributionStatus -notin @('Success','Pending','Failed') }).Count)" -ForegroundColor Gray
Write-Host "===================================================`n" -ForegroundColor White
#endregion
🐙 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.