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.
<#
.SYNOPSIS
Audits Intune-managed devices for compliance with security baselines.
.DESCRIPTION
This script retrieves a list of devices managed by Intune and checks their compliance status
by fetching the associated mobile app policy for each device. Ideal for regular compliance checks.
.NOTES
Author: Souhaiel Morhag
Company: MSEndpoint.com
Blog: https://msendpoint.com
Academy: https://app.msendpoint.com/academy
LinkedIn: https://linkedin.com/in/souhaiel-morhag
GitHub: https://github.com/Msendpoint
License: MIT
.EXAMPLE
.\Audit-IntuneCompliance.ps1
#>
[CmdletBinding()]
param ()
try {
# Retrieve all Intune managed devices
$devices = Get-IntuneManagedDevice
# Check compliance for each device
foreach ($device in $devices) {
# Fetch mobile app policy for the current device
$compliancePolicy = Get-IntuneMobileAppPolicy -DeviceId $device.Id
Write-Output "Device ID: $($device.Id), Compliance Status: $($compliancePolicy.Status)"
}
} catch {
Write-Error "An error occurred: $_"
}
Outlook Hyperlink Warning Remediation and Trusted Sites Configuration via Intune
Detects and remediates Outlook and Office hyperlink security warnings while configuring trusted sites in the Internet Zone registry via Intune Proactive Remediation scripts.
Monitor Sensitivity Label Policy Sync Status in Microsoft Purview
Connects to Security & Compliance PowerShell and reports the distribution/sync status of all sensitivity label publishing policies, highlighting any that are not yet fully propagated.
<#
.SYNOPSIS
Monitors and reports the sync/distribution status of all sensitivity label publishing policies in Microsoft Purview.
.DESCRIPTION
This script connects to the Security & Compliance PowerShell endpoint using the
ExchangeOnlineManagement module and retrieves all sensitivity label publishing policies
along with their DistributionStatus property.
It is designed to help Microsoft Purview / Information Protection administrators:
- Confirm that policy changes have fully propagated across Microsoft 365 infrastructure.
- Identify policies that are still in a Pending or failed state after a change.
- Automate post-change validation as part of a change management or compliance workflow.
The DistributionStatus field returns one of the following values:
- Success : Policy is fully distributed and live for all targeted users.
- Pending : Policy change is queued or propagation has not yet completed.
- Failed : An error occurred during distribution; immediate investigation recommended.
This script is especially useful in regulated environments where you need to confirm
that a sensitivity label policy is in force before closing a change management ticket
or meeting a compliance deadline.
.NOTES
Author: Souhaiel Morhag
Company: MSEndpoint.com
Blog: https://msendpoint.com
Academy: https://app.msendpoint.com/academy
LinkedIn: https://linkedin.com/in/souhaiel-morhag
GitHub: https://github.com/Msendpoint
License: MIT
.PARAMETER UserPrincipalName
The UPN of the admin account used to authenticate to Security & Compliance PowerShell.
Must have Compliance Administrator or Global Administrator rights.
.PARAMETER ShowAllPolicies
Switch parameter. When specified, the script outputs ALL policies regardless of status.
By default, only policies that are NOT in a 'Success' state are highlighted.
.EXAMPLE
# Run the script and show only non-successful (pending/failed) policies:
.\Get-LabelPolicySyncStatus.ps1 -UserPrincipalName admin@yourtenant.onmicrosoft.com
.EXAMPLE
# Run the script and show ALL policies including successfully synced ones:
.\Get-LabelPolicySyncStatus.ps1 -UserPrincipalName admin@yourtenant.onmicrosoft.com -ShowAllPolicies
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, HelpMessage = 'Enter the UPN of the compliance/global admin account.')]
[ValidateNotNullOrEmpty()]
[string]$UserPrincipalName,
[Parameter(Mandatory = $false, HelpMessage = 'Show all policies, including successfully synced ones.')]
[switch]$ShowAllPolicies
)
#region --- Module Check and Installation ---
Write-Host "[INFO] Checking for ExchangeOnlineManagement module..." -ForegroundColor Cyan
try {
if (-not (Get-Module -ListAvailable -Name ExchangeOnlineManagement)) {
Write-Host "[INFO] ExchangeOnlineManagement module not found. Installing for current user..." -ForegroundColor Yellow
Install-Module -Name ExchangeOnlineManagement -Force -Scope CurrentUser -ErrorAction Stop
Write-Host "[INFO] Module installed successfully." -ForegroundColor Green
} else {
Write-Host "[INFO] ExchangeOnlineManagement module is already installed." -ForegroundColor Green
}
} catch {
Write-Error "[ERROR] Failed to install ExchangeOnlineManagement module. Please install it manually. Details: $_"
exit 1
}
#endregion
#region --- Connect to Security & Compliance PowerShell ---
Write-Host "[INFO] Connecting to Security & Compliance PowerShell as '$UserPrincipalName'..." -ForegroundColor Cyan
try {
Connect-IPPSSession -UserPrincipalName $UserPrincipalName -ErrorAction Stop
Write-Host "[INFO] Successfully connected to Security & Compliance PowerShell." -ForegroundColor Green
} catch {
Write-Error "[ERROR] Failed to connect to Security & Compliance PowerShell. Details: $_"
exit 1
}
#endregion
#region --- Retrieve Label Policies ---
Write-Host "[INFO] Retrieving all sensitivity label publishing policies..." -ForegroundColor Cyan
try {
$allPolicies = Get-LabelPolicy -ErrorAction Stop | Select-Object -Property Name, Guid, DistributionStatus, LastModifiedTime, WhenCreated
} catch {
Write-Error "[ERROR] Failed to retrieve label policies. Ensure the account has the required permissions. Details: $_"
exit 1
}
if (-not $allPolicies) {
Write-Warning "[WARN] No sensitivity label policies were found in this tenant."
exit 0
}
Write-Host "[INFO] Total policies retrieved: $($allPolicies.Count)" -ForegroundColor Cyan
#endregion
#region --- Display All Policies (if requested) ---
if ($ShowAllPolicies) {
Write-Host "`n=== ALL Sensitivity Label Policies ===" -ForegroundColor White
$allPolicies | Format-Table -AutoSize
}
#endregion
#region --- Identify Non-Successful Policies ---
Write-Host "`n[INFO] Checking for policies that are NOT in a 'Success' state..." -ForegroundColor Cyan
# Filter for any policy that has not fully synced
$pendingPolicies = $allPolicies | Where-Object { $_.DistributionStatus -ne 'Success' }
if ($pendingPolicies.Count -eq 0) {
Write-Host "[SUCCESS] All sensitivity label policies have a DistributionStatus of 'Success'. No action required." -ForegroundColor Green
} else {
Write-Warning "[WARN] The following $($pendingPolicies.Count) policy/policies have NOT completed distribution:"
$pendingPolicies | Format-Table -AutoSize
# Separate and call out any explicitly failed policies for immediate attention
$failedPolicies = $pendingPolicies | Where-Object { $_.DistributionStatus -eq 'Failed' }
if ($failedPolicies.Count -gt 0) {
Write-Host "`n[CRITICAL] The following policies have a 'Failed' distribution status and require immediate investigation:" -ForegroundColor Red
$failedPolicies | Format-Table -AutoSize
}
}
#endregion
#region --- Summary Report ---
Write-Host "`n=== Sensitivity Label Policy Sync Status Summary ===" -ForegroundColor White
Write-Host "Total Policies : $($allPolicies.Count)"
Write-Host "Successful : $(($allPolicies | Where-Object { $_.DistributionStatus -eq 'Success' }).Count)" -ForegroundColor Green
Write-Host "Pending : $(($allPolicies | Where-Object { $_.DistributionStatus -eq 'Pending' }).Count)" -ForegroundColor Yellow
Write-Host "Failed : $(($allPolicies | Where-Object { $_.DistributionStatus -eq 'Failed' }).Count)" -ForegroundColor Red
Write-Host "Other/Unknown : $(($allPolicies | Where-Object { $_.DistributionStatus -notin @('Success','Pending','Failed') }).Count)" -ForegroundColor Gray
Write-Host "===================================================`n" -ForegroundColor White
#endregion
Export Microsoft Edge Intune Security Baseline Assignments
Connects to Microsoft Graph and exports all Microsoft Edge Security Baseline assignments from Intune, displaying each baseline name and its target group or scope for documentation and auditing purposes.
<#
.SYNOPSIS
Exports Microsoft Edge Intune Security Baseline assignments for documentation and auditing.
.DESCRIPTION
This script connects to Microsoft Graph using the Microsoft Graph PowerShell SDK and retrieves
all Device Management Intents (Security Baselines) whose display name contains 'Edge'.
For each matching baseline, it enumerates all assignments and outputs the baseline name
alongside each assignment target type.
This is useful for IT administrators and security teams who want to document which Edge
Security Baselines are deployed in their Intune tenant and verify assignment targets
(e.g., specific AAD groups, all devices, all users) as part of a compliance or
change management process.
Prerequisites:
- Microsoft Graph PowerShell SDK installed:
Install-Module Microsoft.Graph -Scope CurrentUser
- Sufficient Intune permissions in Entra ID (at minimum DeviceManagement.Read.All)
- PowerShell 5.1+ or PowerShell 7+
.NOTES
Author: Souhaiel Morhag
Company: MSEndpoint.com
Blog: https://msendpoint.com
Academy: https://app.msendpoint.com/academy
LinkedIn: https://linkedin.com/in/souhaiel-morhag
GitHub: https://github.com/Msendpoint
License: MIT
.EXAMPLE
# Run interactively with default parameters (outputs to console)
.\Export-EdgeBaselineAssignments.ps1
.EXAMPLE
# Run and redirect output to a text file for documentation
.\Export-EdgeBaselineAssignments.ps1 | Tee-Object -FilePath .\EdgeBaselineAssignments.txt
.EXAMPLE
# Run with a custom keyword filter to find baselines with a different naming convention
.\Export-EdgeBaselineAssignments.ps1 -BaselineFilter "Browser"
#>
[CmdletBinding()]
param (
# Filter string used to search for Edge-related Security Baselines by display name.
# Defaults to 'Edge' to match Microsoft's standard baseline naming.
[Parameter(Mandatory = $false)]
[string]$BaselineFilter = "Edge",
# Optional: Export results to a CSV file at the specified path.
[Parameter(Mandatory = $false)]
[string]$ExportCsvPath = ""
)
#region --- Functions ---
function Connect-ToMicrosoftGraph {
<#
.SYNOPSIS
Authenticates to Microsoft Graph with the required Intune read scopes.
#>
[CmdletBinding()]
param ()
Write-Verbose "Connecting to Microsoft Graph with scope: DeviceManagement.Read.All"
try {
Connect-MgGraph -Scopes "DeviceManagement.Read.All" -ErrorAction Stop
Write-Verbose "Successfully connected to Microsoft Graph."
}
catch {
Write-Error "Failed to connect to Microsoft Graph. Ensure the Microsoft.Graph module is installed and you have appropriate permissions.`nError: $_"
exit 1
}
}
function Get-EdgeBaselines {
<#
.SYNOPSIS
Retrieves Device Management Intents (Security Baselines) matching the specified filter.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$Filter
)
Write-Verbose "Querying Device Management Intents with filter: '*$Filter*'"
try {
$baselines = Get-MgDeviceManagementIntent -ErrorAction Stop | Where-Object {
$_.DisplayName -like "*$Filter*"
}
if (-not $baselines) {
Write-Warning "No Security Baselines found matching filter: '$Filter'. Verify the baseline exists in your tenant."
}
else {
Write-Verbose "Found $($baselines.Count) baseline(s) matching filter '$Filter'."
}
return $baselines
}
catch {
Write-Error "Failed to retrieve Device Management Intents.`nError: $_"
return $null
}
}
function Get-BaselineAssignments {
<#
.SYNOPSIS
Retrieves assignments for a given Device Management Intent (Security Baseline).
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$IntentId
)
try {
$assignments = Get-MgDeviceManagementIntentAssignment `
-DeviceManagementIntentId $IntentId `
-ErrorAction Stop
return $assignments
}
catch {
Write-Warning "Failed to retrieve assignments for Intent ID: $IntentId.`nError: $_"
return @()
}
}
#endregion --- Functions ---
#region --- Main Execution ---
Write-Output "=== Edge Security Baseline Assignment Export ==="
Write-Output "Filter: '$BaselineFilter'"
Write-Output "Timestamp: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
Write-Output "-------------------------------------------------"
# Step 1: Authenticate to Microsoft Graph
Connect-ToMicrosoftGraph
# Step 2: Retrieve all Edge-related Security Baselines
$baselines = Get-EdgeBaselines -Filter $BaselineFilter
if (-not $baselines) {
Write-Output "No baselines found. Exiting."
Disconnect-MgGraph | Out-Null
exit 0
}
# Step 3: Collect results for optional CSV export
$results = [System.Collections.Generic.List[PSCustomObject]]::new()
# Step 4: Iterate over each baseline and retrieve its assignments
foreach ($baseline in $baselines) {
Write-Output ""
Write-Output "Baseline : $($baseline.DisplayName)"
Write-Output "Intent ID: $($baseline.Id)"
$assignments = Get-BaselineAssignments -IntentId $baseline.Id
if (-not $assignments -or $assignments.Count -eq 0) {
Write-Output " -> No assignments found for this baseline."
# Record in results list even if unassigned
$results.Add([PSCustomObject]@{
BaselineName = $baseline.DisplayName
IntentId = $baseline.Id
AssignmentId = "N/A"
TargetType = "No Assignments"
})
}
else {
foreach ($assignment in $assignments) {
# Extract the OData type which identifies the assignment target
# e.g., #microsoft.graph.allDevicesAssignmentTarget,
# #microsoft.graph.groupAssignmentTarget, etc.
$targetType = $assignment.Target.AdditionalProperties['@odata.type']
# Attempt to extract group ID if it is a group-based assignment
$groupId = $assignment.Target.AdditionalProperties['groupId']
$targetDisplay = if ($groupId) {
"$targetType (GroupId: $groupId)"
}
else {
$targetType
}
Write-Output " -> Assignment ID : $($assignment.Id)"
Write-Output " Target Type : $targetDisplay"
$results.Add([PSCustomObject]@{
BaselineName = $baseline.DisplayName
IntentId = $baseline.Id
AssignmentId = $assignment.Id
TargetType = $targetDisplay
})
}
}
}
# Step 5: Optionally export to CSV
if ($ExportCsvPath -ne "") {
try {
$results | Export-Csv -Path $ExportCsvPath -NoTypeInformation -Encoding UTF8 -ErrorAction Stop
Write-Output ""
Write-Output "Results exported to CSV: $ExportCsvPath"
}
catch {
Write-Warning "Failed to export CSV to '$ExportCsvPath'.`nError: $_"
}
}
Write-Output ""
Write-Output "-------------------------------------------------"
Write-Output "Export complete. Total baselines processed: $($baselines.Count)"
# Step 6: Disconnect from Microsoft Graph cleanly
try {
Disconnect-MgGraph | Out-Null
Write-Verbose "Disconnected from Microsoft Graph."
}
catch {
Write-Verbose "Note: Could not explicitly disconnect from Microsoft Graph: $_"
}
#endregion --- Main Execution ---
Deploy Always-Updated Google Chrome via Intune Win32 App
Downloads and silently installs the latest Google Chrome directly from Google's official source, designed for Intune Win32 app deployment via Company Portal.
<#
.SYNOPSIS
Downloads and silently installs the latest version of Google Chrome from Google's official source.
.DESCRIPTION
This script is designed to be packaged as an Intune Win32 app and deployed via Microsoft Endpoint Manager
(Microsoft Intune) Company Portal. It fetches the most current Chrome installer directly from Google's
official CDN URL, which always points to the latest available version. The installer runs silently
with no user interaction required, and the installer file is cleaned up after installation.
By using the dynamic Google CDN URL instead of a static versioned installer, this approach ensures
that every device enrollment or app deployment always receives the latest secure version of Chrome,
eliminating the need for manual Intune app updates each time a new Chrome version is released.
Intended usage:
- Install Command : powershell.exe -ExecutionPolicy Bypass -File InstallChrome.ps1
- Uninstall Command: powershell.exe -ExecutionPolicy Bypass -File UninstallChrome.ps1
- Detection Rule : File or registry rule confirming chrome.exe presence in Program Files\Google\Chrome
.NOTES
Author: Souhaiel Morhag
Company: MSEndpoint.com
Blog: https://msendpoint.com
Academy: https://app.msendpoint.com/academy
LinkedIn: https://linkedin.com/in/souhaiel-morhag
GitHub: https://github.com/Msendpoint
License: MIT
.EXAMPLE
# Run locally or via Intune Win32 install command:
powershell.exe -ExecutionPolicy Bypass -File InstallChrome.ps1
.EXAMPLE
# Run uninstall script via Intune Win32 uninstall command:
powershell.exe -ExecutionPolicy Bypass -File UninstallChrome.ps1
#>
[CmdletBinding()]
param()
#region --- INSTALL SCRIPT ---
# Define the official Google CDN URL that always resolves to the latest Chrome installer
$chromeInstallerUrl = "https://dl.google.com/chrome/install/latest/chrome_installer.exe"
# Define a temporary staging folder and full path for the downloaded installer
$installerFolder = "C:\Temp"
$installerPath = Join-Path -Path $installerFolder -ChildPath "chrome_installer.exe"
try {
# Ensure the temporary staging folder exists; create it silently if it does not
if (-Not (Test-Path -Path $installerFolder)) {
Write-Verbose "Staging folder '$installerFolder' not found. Creating it now."
New-Item -ItemType Directory -Path $installerFolder -Force | Out-Null
}
# Download the latest Chrome installer from the official Google source
Write-Verbose "Downloading Chrome installer from: $chromeInstallerUrl"
Invoke-WebRequest -Uri $chromeInstallerUrl -OutFile $installerPath -UseBasicParsing
# Verify the installer was downloaded successfully before proceeding
if (-Not (Test-Path -Path $installerPath)) {
throw "Installer download failed. File not found at '$installerPath'."
}
# Execute the Chrome installer silently with no user prompts
Write-Verbose "Starting silent Chrome installation..."
$process = Start-Process -FilePath $installerPath -ArgumentList "/silent /install" -Wait -PassThru
if ($process.ExitCode -ne 0) {
throw "Chrome installer exited with non-zero exit code: $($process.ExitCode)."
}
Write-Output "Google Chrome installed successfully."
}
catch {
Write-Error "An error occurred during Chrome installation: $_"
exit 1
}
finally {
# Always attempt to clean up the installer file regardless of success or failure
if (Test-Path -Path $installerPath) {
Write-Verbose "Removing installer file: $installerPath"
Remove-Item -Path $installerPath -Force -ErrorAction SilentlyContinue
}
}
#endregion --- INSTALL SCRIPT ---