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

6 scripts matching your filters · Browse guides with scripts →

PowerShellMicrosoft GraphPHP

Teams and Entra Conditional Access Automation

Scripts automate the deployment of Teams scam detection and Entra Conditional Access.

📖 Full guide: Enhancing Teams Security: Facilitator's Scam Detection Unveiled
### FILE: index.php
<?php 

session_start();
$accessToken = $_SESSION['ms_access_token'];

try {
    // Call to fetch current Conditional Access Policies
    $endpoint = '/identity/conditionalAccess/policies';
    $policies = $ms->graphCall($endpoint, $accessToken);
    
    foreach ($policies as $policy) {
        render_premium_card(
            $policy['displayName'],
            'Enabled: ' . ($policy['state'] == 'enabled' ? 'Yes' : 'No'),
            null, 'up', '🔐'
        );
    }
    
} catch (Exception $e) {
    echo 'Error fetching policies: ' . $e->getMessage();
}

?>

### FILE: scripts/EntraConditionalAccess.ps1
<#
.SYNOPSIS
   Configures a Conditional Access policy for enhanced security in Entra ID.
.DESCRIPTION
   This script connects to Microsoft Graph and creates a Conditional Access Policy for token protection.
.EXAMPLE
   .\EntraConditionalAccess.ps1
.NOTES
   Author:      Souhaiel Morhag
   Company:     MSEndpoint.com
   Blog:        https://msendpoint.com
   Academy:     https://app.msendpoint.com/academy
   LinkedIn:    https://linkedin.com/in/souhaiel-morhag
   GitHub:      https://github.com/Msendpoint
   License:     MIT
#>

try {
    Connect-MgGraph -Scopes "Policy.ReadWrite.ConditionalAccess"
    
    $policy = @{
        displayName = "Entra Token Protection Policy"
        conditions   = @{
            users     = @{
                includeUsers = @( 'All' )
            }
        }
        grantControls = @{
            builtIns = @( 'bi_tokenProtection' )
        }
        state         = 'enabled'
    }
    
    New-MgConditionalAccessPolicy -BodyParameter $policy
    Write-Host "Conditional Access policy created successfully."
} catch {
    Write-Error "Failed to create policy: $_"
}
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 Graph SDK

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.

📖 Full guide: Securing the Browser Era: How to Protect the Modern Workspace with Microsoft In…
<#
.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 ---
🐙 GitHub
PowerShellMicrosoft IntuneWin32 App Packaging

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.

📖 Full guide: Deploy Always-Updated Google Chrome via Intune Company Portal (Win32 App)
<#
.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 ---
🐙 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.