diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..327fc20 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,80 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + analyze: + name: PSScriptAnalyzer + runs-on: windows-latest + timeout-minutes: 15 + steps: + # Every action is pinned to a full commit SHA. The comment names the tag it was taken from. + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + + - name: Install PSScriptAnalyzer + shell: pwsh + run: | + Set-PSRepository -Name PSGallery -InstallationPolicy Trusted + Install-Module -Name PSScriptAnalyzer -RequiredVersion 1.25.0 -Scope CurrentUser -Force + + # Per file, because a whole-tree run printed an internal NullReference in the audit. + # Tests\ is skipped: Pester mock bodies cannot see $script: variables, so the tests use one $global: table on purpose. + - name: Run PSScriptAnalyzer + shell: pwsh + run: | + Import-Module PSScriptAnalyzer -RequiredVersion 1.25.0 + $files = Get-ChildItem -Recurse -File -Include *.ps1, *.psm1, *.psd1 | + Where-Object { $_.FullName -notlike '*\Tests\*' -and $_.FullName -notlike '*\.git\*' } + $results = foreach ($file in $files) { + Invoke-ScriptAnalyzer -Path $file.FullName -Settings ./PSScriptAnalyzerSettings.psd1 + } + Write-Host "Analyzed $($files.Count) file(s)." + if ($results) { + $results | Format-Table -AutoSize ScriptName, Line, RuleName, Severity, Message | Out-String -Width 250 | Write-Host + throw "PSScriptAnalyzer reported $(@($results).Count) finding(s)." + } + + test: + name: Pester (${{ matrix.shell }}) + runs-on: windows-latest + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + # pwsh is PowerShell 7. powershell is Windows PowerShell 5.1, which is what Intune runs. + shell: [pwsh, powershell] + defaults: + run: + shell: ${{ matrix.shell }} + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + + - name: Install Pester + run: | + Set-PSRepository -Name PSGallery -InstallationPolicy Trusted + # -SkipPublisherCheck: Windows PowerShell 5.1 ships Pester 3.4 signed by Microsoft + Install-Module -Name Pester -RequiredVersion 5.9.1 -Scope CurrentUser -Force -SkipPublisherCheck + + - name: Parse every script + run: | + $errors = foreach ($file in Get-ChildItem -Recurse -File -Include *.ps1, *.psm1, *.psd1 | Where-Object { $_.FullName -notlike '*\.git\*' }) { + $tokens = $null; $parseErrors = $null + [System.Management.Automation.Language.Parser]::ParseFile($file.FullName, [ref]$tokens, [ref]$parseErrors) | Out-Null + foreach ($e in $parseErrors) { "$($file.Name):$($e.Extent.StartLineNumber) $($e.Message)" } + } + if ($errors) { $errors | ForEach-Object { Write-Host $_ }; throw "Parse errors found." } + + - name: Run Pester + run: | + Import-Module Pester -RequiredVersion 5.9.1 + $config = New-PesterConfiguration + $config.Run.Path = './Tests' + $config.Run.Exit = $true + $config.Output.Verbosity = 'Normal' + Invoke-Pester -Configuration $config diff --git a/.gitignore b/.gitignore index 9be6fd7..5735c78 100644 --- a/.gitignore +++ b/.gitignore @@ -29,3 +29,7 @@ desktop.ini .vscode/ .idea/ *.code-workspace + +# Test fixtures are allowed even though the patterns above ignore data files +!Tests/**/*.json +!Tests/**/*.csv diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..48022c0 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,34 @@ +# Changelog + +## Unreleased (fix/audit-2026-11-18) + +Fixes from the 2026-11-18 audit. See the commit messages for the reasoning behind each change. + +### Fixed + +- `Set-OfficeUpdateChannel.ps1`: wrote an array of 15 URLs to `CDNBaseUrl` and always exited 1. It now writes one URL, uses the real Click-to-Run updater and fails if the updater is missing. +- `Enable-` and `Disable-SmartCardLogonEnforcement.ps1`: report real success or failure, verify each write, keep the log, forward `-WhatIf` on the 64-bit relaunch. Enable refuses to run without a working smart card reader unless `-Force` is given. +- `Test-IntuneEnrollment.ps1`: no longer crashes on registry subkeys without a ProviderID. +- `Test-IntuneConnectivity.ps1`: the Intune endpoints are tested; failure to retrieve an endpoint list fails the run. +- `Start-MDMSync.ps1`: requires Windows PowerShell 5.1, reads `ExtendedError`, and returns the documented timeout code. +- Reporting scripts: unassigned policies are listed, failed requests show as errors and exit 1, results are paged, device compliance is per device, exclusions are labelled, and the scripts no longer install the Microsoft.Graph module. +- `Repair-MultipleIntuneMDMCert.ps1` and `Set-OfficeUpdateChannel.ps1`: `-WhatIf` exits 0. +- `Detect-OfficeUpdateChannel.ps1`: separates compliant, not applicable, cannot determine and non-compliant. +- `Get-IntuneDeviceLogs.ps1`: exit code reflects failures. +- `Get-IntuneDeviceHealth.ps1`: no false "unsupported" management agents. + +### Added + +- `-ClientSecretSecure` on the Graph scripts, `Get-IntuneCredential` and related helpers in `IntuneCommon`, and `IntuneCommon.psd1` (version 1.1.0). +- Formula-safe CSV output. +- Pester tests in `Tests\` and a GitHub Actions workflow (PSScriptAnalyzer and Pester, actions pinned to commit SHAs). +- `Get-IntuneAllAppsAssignmentDetails.ps1`: `-ExportCSVpath` and a `TargetType` column. +- `Test-IntuneConnectivity.ps1`: `-IncludeUnlistedEndpoints`. + +### Changed + +- `Remove-ODataInjectionChars` and `Test-ODataFilterInput` double single quotes instead of deleting them. +- `ConvertTo-Array` now has a process block, so it handles each item of a pipeline instead of only the last. Callers that piped several items and relied on that now get all of them. +- `Get-IntuneGraphHeaders` is new on this branch and takes `-AppRegistration`; it is not a change to an existing signature. +- Graph reports use the beta endpoint for `mobileApps/{id}/deviceStatuses` (Win32 per-device install state), because Microsoft documents it only there. +- `Enable-SmartCardLogonEnforcement.ps1` writes `scforceoption` last, only if every other step succeeded, and puts the old value back if its own write or read-back fails. diff --git a/Common/IntuneCommon.psd1 b/Common/IntuneCommon.psd1 new file mode 100644 index 0000000..90bec08 --- /dev/null +++ b/Common/IntuneCommon.psd1 @@ -0,0 +1,37 @@ +@{ + RootModule = 'IntuneCommon.psm1' + ModuleVersion = '1.1.0' + GUID = '6e874e85-9805-4993-9a39-f0a5ec6151d8' + Author = 'NullSpace-BitCradle' + CompanyName = 'NullSpace-BitCradle' + Copyright = '(c) NullSpace-BitCradle. MIT License.' + Description = 'Shared helpers for the Intune PowerShell scripts: Microsoft Graph token request, retry and paging, credential handling, OData escaping and CSV formula safety.' + PowerShellVersion = '5.1' + FunctionsToExport = @( + 'ConvertTo-Array', + 'ConvertTo-ODataStringLiteral', + 'ConvertTo-SafeCsvRecord', + 'Get-GraphAccessToken', + 'Get-GraphApiAllPages', + 'Get-IntuneCredential', + 'Get-IntuneGraphHeaders', + 'Get-IntuneLogPath', + 'Invoke-GraphApiWithRetry', + 'Protect-CsvValue', + 'Remove-ODataInjectionChars', + 'Test-EmailFormat', + 'Test-GuidFormat', + 'Test-ODataFilterInput', + 'Write-StandardError' + ) + CmdletsToExport = @() + VariablesToExport = @() + AliasesToExport = @() + PrivateData = @{ + PSData = @{ + Tags = @('Intune', 'Graph', 'Endpoint') + LicenseUri = 'https://github.com/NullSpace-BitCradle/Intune_PowerShell_Scripts/blob/main/LICENSE' + ProjectUri = 'https://github.com/NullSpace-BitCradle/Intune_PowerShell_Scripts' + } + } +} diff --git a/Common/IntuneCommon.psm1 b/Common/IntuneCommon.psm1 index 00b3122..3ea3593 100644 --- a/Common/IntuneCommon.psm1 +++ b/Common/IntuneCommon.psm1 @@ -7,8 +7,8 @@ including Graph API authentication, retry logic, and common utilities. .NOTES - Version: 1.0 - Author: Intune Scripts Collection + Version: 1.1.0 + Author: NullSpace-BitCradle #> # Function to invoke Graph API with retry logic @@ -128,38 +128,51 @@ function ConvertTo-Array { $InputObject ) - if ($null -eq $InputObject) { - return @() - } - if ($InputObject -is [Array]) { - return $InputObject + process { + if ($null -eq $InputObject) { + return @() + } + if ($InputObject -is [Array]) { + return $InputObject + } + return @($InputObject) } - return @($InputObject) } # Function to get Graph API access token +# Accepts the client secret as a SecureString (preferred) or as a plain string (kept for compatibility). function Get-GraphAccessToken { - [CmdletBinding()] + [CmdletBinding(DefaultParameterSetName='Plain')] param( [Parameter(Mandatory=$true)] [string]$AppId, - + [Parameter(Mandatory=$true)] [string]$TenantId, - - [Parameter(Mandatory=$true)] - [string]$ClientSecret + + [Parameter(Mandatory=$true, ParameterSetName='Plain')] + [string]$ClientSecret, + + [Parameter(Mandatory=$true, ParameterSetName='Secure')] + [securestring]$ClientSecretSecure ) - + try { + $plainSecret = if ($PSCmdlet.ParameterSetName -eq 'Secure') { + [System.Net.NetworkCredential]::new('', $ClientSecretSecure).Password + } + else { + $ClientSecret + } + $body = @{ grant_type = "client_credentials" scope = "https://graph.microsoft.com/.default" client_id = $AppId - client_secret = $ClientSecret + client_secret = $plainSecret } - - $tokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token" -Method Post -Body $body + + $tokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token" -Method Post -Body $body -ErrorAction Stop return $tokenResponse.access_token } catch { @@ -168,6 +181,69 @@ function Get-GraphAccessToken { } } +# Function to resolve the app registration credentials the reporting scripts use. +# Order: parameter, then environment variable (INTUNE_APP_ID, INTUNE_TENANT_ID, INTUNE_CLIENT_SECRET). +# A SecureString secret wins over a plain-string secret. Placeholder values like are rejected. +# Returns AppId, TenantId and the secret as a SecureString. Throws with a message that names what is missing. +function Get-IntuneCredential { + # The secret reaches this function as a plain string when a caller passes -ClientSecret or sets + # INTUNE_CLIENT_SECRET. Converting it to a SecureString here is the point: it is held as a SecureString from now on. + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '', Justification='The input is already plain text (parameter or environment variable); this wraps it immediately.')] + [CmdletBinding()] + param( + [Parameter(Mandatory=$false)] + [string]$AppId, + + [Parameter(Mandatory=$false)] + [string]$TenantId, + + [Parameter(Mandatory=$false)] + [string]$ClientSecret, + + [Parameter(Mandatory=$false)] + [securestring]$ClientSecretSecure + ) + + $resolvedAppId = if ($AppId) { $AppId } elseif ($env:INTUNE_APP_ID) { $env:INTUNE_APP_ID } else { $null } + $resolvedTenantId = if ($TenantId) { $TenantId } elseif ($env:INTUNE_TENANT_ID) { $env:INTUNE_TENANT_ID } else { $null } + + $secret = $null + if ($ClientSecretSecure) { $secret = $ClientSecretSecure } + elseif ($ClientSecret) { $secret = ConvertTo-SecureString -String $ClientSecret -AsPlainText -Force } + elseif ($env:INTUNE_CLIENT_SECRET) { $secret = ConvertTo-SecureString -String $env:INTUNE_CLIENT_SECRET -AsPlainText -Force } + + $plainForCheck = if ($secret) { [System.Net.NetworkCredential]::new('', $secret).Password } else { $null } + + if (-not $resolvedAppId -or -not $resolvedTenantId -or -not $secret -or + $resolvedAppId -match '^<.*>$' -or $resolvedTenantId -match '^<.*>$' -or $plainForCheck -match '^<.*>$') { + throw "Please provide valid credentials via parameters or environment variables (INTUNE_APP_ID, INTUNE_TENANT_ID, INTUNE_CLIENT_SECRET)." + } + + [PSCustomObject]@{ + AppId = $resolvedAppId + TenantId = $resolvedTenantId + ClientSecret = $secret + } +} + +# Function to get the request headers for Graph calls: requests a token and builds the Authorization header. +function Get-IntuneGraphHeaders { + [CmdletBinding()] + param( + # The object Get-IntuneCredential returns: AppId, TenantId and the secret as a SecureString + [Parameter(Mandatory=$true)] + $AppRegistration + ) + + $token = Get-GraphAccessToken -AppId $AppRegistration.AppId -TenantId $AppRegistration.TenantId -ClientSecretSecure $AppRegistration.ClientSecret + if (-not $token) { throw "The token endpoint returned no access token." } + + return @{ + "Authorization" = "Bearer $token" + "Content-Type" = "application/json" + } +} + # Function to validate GUID format function Test-GuidFormat { [CmdletBinding()] @@ -190,41 +266,92 @@ function Test-EmailFormat { return $Email -match '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$' } -# Function to sanitize input for OData queries +# Function to turn a value into an OData string literal: wrapped in single quotes, with each +# single quote doubled. Doubling is OData's escape. Deleting the quote (the old behaviour of +# Remove-ODataInjectionChars) changed the value, so a name with an apostrophe never matched. +# Build the filter with this, then URL-encode the whole filter with [uri]::EscapeDataString. +function ConvertTo-ODataStringLiteral { + [CmdletBinding()] + param( + [Parameter(Mandatory=$true)] + [string]$Value + ) + + return "'" + ($Value -replace "'", "''") + "'" +} + +# Function to escape input for OData queries. Returns the value with single quotes doubled +# (no surrounding quotes). See ConvertTo-ODataStringLiteral. function Remove-ODataInjectionChars { + # Despite the verb, this only returns an escaped copy of a string. It changes no system state. + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification='Pure string function.')] [CmdletBinding()] param( [Parameter(Mandatory=$true)] [string]$InputString ) - - # Remove potentially dangerous characters from OData filter - return $InputString -replace "[';]", "" + + return ($InputString -replace "'", "''") } -# Function to validate and sanitize OData filter input +# Function to validate and escape OData filter input function Test-ODataFilterInput { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [string]$InputString, - + [Parameter(Mandatory=$false)] [switch]$AllowWildcards ) - - # Remove potentially dangerous characters from OData filter - $sanitized = $InputString -replace "[';]", "" - + + $sanitized = $InputString + + # contains() and eq are literal matches in Graph, so a wildcard character is never a wildcard if (-not $AllowWildcards) { $sanitized = $sanitized -replace "[*%]", "" } - + if ([string]::IsNullOrWhiteSpace($sanitized)) { throw "Input string cannot be empty after sanitization." } - - return $sanitized + + return ($sanitized -replace "'", "''") +} + +# Function to neutralise spreadsheet formulas in one CSV value. A cell that starts with = + - @ or a +# tab or carriage return is run as a formula by Excel; a leading apostrophe makes it plain text. +function Protect-CsvValue { + [CmdletBinding()] + param( + [Parameter(Mandatory=$false)] + [AllowNull()] + [AllowEmptyString()] + [string]$Value + ) + + if ($Value -and $Value -match '^[=+\-@\t\r]') { return "'" + $Value } + return $Value +} + +# Function to apply Protect-CsvValue to every string property of the objects passed in. +# Use it just before Export-Csv: $rows | ConvertTo-SafeCsvRecord | Export-Csv ... +function ConvertTo-SafeCsvRecord { + [CmdletBinding()] + param( + [Parameter(ValueFromPipeline=$true, Mandatory=$true)] + $InputObject + ) + + process { + $record = [ordered]@{} + foreach ($property in $InputObject.PSObject.Properties) { + $value = $property.Value + if ($value -is [string]) { $value = Protect-CsvValue -Value $value } + $record[$property.Name] = $value + } + [PSCustomObject]$record + } } # Function to get Intune log path @@ -283,5 +410,5 @@ function Write-StandardError { } # Export module members -Export-ModuleMember -Function Invoke-GraphApiWithRetry, Get-GraphAccessToken, Test-GuidFormat, Test-EmailFormat, Remove-ODataInjectionChars, Get-GraphApiAllPages, ConvertTo-Array, Test-ODataFilterInput, Get-IntuneLogPath, Write-StandardError +Export-ModuleMember -Function Invoke-GraphApiWithRetry, Get-GraphAccessToken, Get-IntuneCredential, Get-IntuneGraphHeaders, Test-GuidFormat, Test-EmailFormat, ConvertTo-ODataStringLiteral, Remove-ODataInjectionChars, Get-GraphApiAllPages, ConvertTo-Array, Test-ODataFilterInput, Protect-CsvValue, ConvertTo-SafeCsvRecord, Get-IntuneLogPath, Write-StandardError diff --git a/Detection/Detect-MultipleIntuneMDMCert.ps1 b/Detection/Detect-MultipleIntuneMDMCert.ps1 index 66c90fd..17462f7 100644 --- a/Detection/Detect-MultipleIntuneMDMCert.ps1 +++ b/Detection/Detect-MultipleIntuneMDMCert.ps1 @@ -5,7 +5,7 @@ .DESCRIPTION This script checks the Local Machine certificate store for multiple Intune MDM Device CA certificates. If more than one certificate is found, it indicates a remediation is needed. - Used as a detection script in Intune compliance policies or remediation scripts. + Use it as the detection script of an Intune Remediation (exit 0 = fine, exit 1 = run the remediation). It is not a custom compliance script: that needs JSON output. .EXAMPLE .\Detect-MultipleIntuneMDMCert.ps1 diff --git a/Detection/Detect-OfficeUpdateChannel.ps1 b/Detection/Detect-OfficeUpdateChannel.ps1 index c480b16..77977ee 100644 --- a/Detection/Detect-OfficeUpdateChannel.ps1 +++ b/Detection/Detect-OfficeUpdateChannel.ps1 @@ -7,120 +7,163 @@ and is on the latest version. It reads the local Office configuration from the registry and compares it with the latest available version from Microsoft's cloud service. + It is the detection half of an Intune Remediation (proactive remediation) and follows that + contract: exit 0 means no remediation is needed, exit 1 means the remediation script should run. + Four outcomes are kept apart: + - Compliant: Semi-Annual channel and latest version. Exit 0. + - Not applicable: Office Click-to-Run is not installed. Exit 0, so the device is not + sent to a remediation that cannot succeed. + - Cannot determine: the registry or Microsoft's release service could not be read. Exit 0 + with a message, so a missing network does not trigger remediation on every cycle. + - Non-compliant: wrong channel or an older build. Exit 1. + + Run the script in 64-bit PowerShell. If it is started in a 32-bit host on a 64-bit system it + relaunches itself in 64-bit PowerShell. + .EXAMPLE .\Detect-OfficeUpdateChannel.ps1 .NOTES + Intune Remediations contract: set "Run script in 64-bit PowerShell" to Yes. Exit Codes: - - 0: Office is on Semi-Annual channel and latest version - - 1: Office is not on Semi-Annual channel or not on latest version, or error occurred + - 0: Compliant, not applicable, or cannot determine (see the message) + - 1: Office is not on the Semi-Annual channel or not on the latest version #> [CmdletBinding()] param() -# Main script execution wrapped in try-catch for error handling -try -{ - # Read the currently installed Office version from the registry - # This value is reported by Office Click-to-Run installation - $ReportedVersion = Get-ItemPropertyValue -Path "HKLM:\SOFTWARE\Microsoft\Office\ClickToRun\Configuration" -Name "VersionToReport" - - # Read the CDN (Content Delivery Network) base URL from the registry - # This URL indicates which update channel Office is configured to use - # Select-Object -Last 1 ensures we get the most recent value if multiple exist - $Channel = Get-ItemPropertyValue -Path "HKLM:\SOFTWARE\Microsoft\Office\ClickToRun\Configuration" -Name "CDNBaseUrl" | Select-Object -Last 1 - - # Function to invoke Office API with retry logic - # Handles transient failures (429, 503, etc.) with exponential backoff - function Invoke-OfficeApiWithRetry { - [CmdletBinding()] - param( - [Parameter(Mandatory=$true)] - [string]$Uri, - - [Parameter(Mandatory=$false)] - [int]$MaxRetries = 3, - - [Parameter(Mandatory=$false)] - [int]$InitialDelaySeconds = 2 - ) - - $retryCount = 0 - $delaySeconds = $InitialDelaySeconds - - while ($retryCount -le $MaxRetries) { - try { - $response = Invoke-RestMethod -Uri $Uri -ErrorAction Stop - return $response +# Build the argument list used to relaunch this script in 64-bit PowerShell. +function Get-RelaunchArgumentList { + [CmdletBinding()] + param( + [Parameter(Mandatory=$true)] + [string]$ScriptPath, + + [Parameter(Mandatory=$false)] + [hashtable]$BoundParameters = @{} + ) + + $arguments = @('-ExecutionPolicy', 'Bypass', '-NoProfile', '-File', $ScriptPath) + foreach ($key in $BoundParameters.Keys) { + $value = $BoundParameters[$key] + if ($value -is [System.Management.Automation.SwitchParameter]) { + if ($value.IsPresent) { $arguments += "-$key" } + } + } + return $arguments +} + +# Function to invoke Office API with retry logic +# Handles transient failures (429, 503, etc.) with exponential backoff +function Invoke-OfficeApiWithRetry { + [CmdletBinding()] + param( + [Parameter(Mandatory=$true)] + [string]$Uri, + + [Parameter(Mandatory=$false)] + [int]$MaxRetries = 3, + + [Parameter(Mandatory=$false)] + [int]$InitialDelaySeconds = 2 + ) + + $retryCount = 0 + $delaySeconds = $InitialDelaySeconds + + while ($retryCount -le $MaxRetries) { + try { + $response = Invoke-RestMethod -Uri $Uri -ErrorAction Stop + return $response + } + catch { + $statusCode = $null + if ($_.Exception.Response) { $statusCode = [int]$_.Exception.Response.StatusCode } + + # Retryable: 429 Too Many Requests, 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout + if ($statusCode -in @(429, 502, 503, 504) -and $retryCount -lt $MaxRetries) { + $retryCount++ + Write-Verbose "Office API call failed with status $statusCode. Retrying in $delaySeconds seconds (attempt $retryCount of $MaxRetries)..." + Start-Sleep -Seconds $delaySeconds + $delaySeconds = $delaySeconds * 2 } - catch { - $statusCode = $_.Exception.Response.StatusCode.value__ - - # Check if this is a retryable error (429 Too Many Requests, 503 Service Unavailable, 502 Bad Gateway, 504 Gateway Timeout) - if ($statusCode -in @(429, 502, 503, 504) -and $retryCount -lt $MaxRetries) { - $retryCount++ - Write-Verbose "Office API call failed with status $statusCode. Retrying in $delaySeconds seconds (attempt $retryCount of $MaxRetries)..." - Start-Sleep -Seconds $delaySeconds - # Exponential backoff: double the delay for next retry - $delaySeconds = $delaySeconds * 2 - } - else { - # Not a retryable error or max retries reached - throw - } + else { + throw } } } - +} + +# Architecture check: if running as a 32-bit process on a 64-bit system, relaunch as 64-bit. +# Intune Remediations run in 32-bit PowerShell unless told otherwise, and a 32-bit host can be +# redirected to WOW6432Node when it reads HKLM\SOFTWARE. +if ($env:PROCESSOR_ARCHITEW6432 -and $env:PROCESSOR_ARCHITEW6432 -ne "ARM64") +{ + $sysNativePowerShell = "$($env:WINDIR)\SysNative\WindowsPowerShell\v1.0\powershell.exe" + if (Test-Path $sysNativePowerShell) + { + $relaunchArguments = Get-RelaunchArgumentList -ScriptPath $PSCommandPath -BoundParameters $PSBoundParameters + & $sysNativePowerShell @relaunchArguments + exit $LASTEXITCODE + } +} + +$officeConfigPath = "HKLM:\SOFTWARE\Microsoft\Office\ClickToRun\Configuration" + +# Main script execution wrapped in try-catch for error handling +try +{ + # No Click-to-Run means there is no channel to check. Not applicable, so do not trigger remediation. + if (-not (Test-Path -Path $officeConfigPath)) { + Write-Output "Not applicable: Office Click-to-Run is not installed." + exit 0 + } + + # Read the currently installed Office version and the CDN base URL (which identifies the channel) + $ReportedVersion = Get-ItemPropertyValue -Path $officeConfigPath -Name "VersionToReport" -ErrorAction Stop + $Channel = Get-ItemPropertyValue -Path $officeConfigPath -Name "CDNBaseUrl" -ErrorAction Stop | Select-Object -Last 1 + # Query Microsoft's Office release information service to get the latest available versions - # This provides up-to-date information about all Office update channels and their latest versions $CloudVersionInfo = Invoke-OfficeApiWithRetry -Uri 'https://clients.config.office.net/releases/v1.0/OfficeReleases' - - # Filter the cloud version information to find the channel that matches the local CDN URL - # This identifies which update channel the local Office installation is using - $UsedChannel = $CloudVersionInfo | Where-Object { $_.OfficeVersions.cdnBaseURL -eq $Channel } - - # Check if channel was found in cloud version information + + # Find the channel that matches the local CDN URL + $UsedChannel = @($CloudVersionInfo | Where-Object { $_.OfficeVersions.cdnBaseUrl -contains $Channel }) | Select-Object -First 1 + if ($null -eq $UsedChannel) { - Write-Error "Could not determine Office update channel from cloud service. Channel URL: $Channel" + # The local CDN URL is not one Microsoft lists, which is itself a wrong configuration for this policy + Write-Output "Non-compliant: the configured update channel ($Channel) is not a Microsoft-listed channel." exit 1 } - - # Handle array results - ensure we have a single channel result - if ($UsedChannel -is [Array]) { - if ($UsedChannel.Count -gt 1) { - Write-Warning "Multiple channels found matching CDN URL. Using first result." - } - $UsedChannel = $UsedChannel[0] - } - - # Check if the detected channel is Semi-Annual and if the installed version matches the latest version - # Both conditions must be true for the check to pass - if (($UsedChannel.channelId -eq "SemiAnnual") -and ($UsedChannel.latestversion -eq $ReportedVersion)) { - # Office is on Semi-Annual channel and latest version - compliance check passes - Write-Host "Currently using the latest version of Office in the $($UsedChannel.channelId) Channel: $($ReportedVersion)" + + $onSemiAnnual = ($UsedChannel.channelId -eq "SemiAnnual") + $onLatest = ($UsedChannel.latestversion -eq $ReportedVersion) + + if ($onSemiAnnual -and $onLatest) { + Write-Output "Compliant: using the latest version of Office in the $($UsedChannel.channelId) Channel: $ReportedVersion" exit 0 } + elseif (-not $onSemiAnnual) { + Write-Output "Non-compliant: not using the Semi-Annual channel. Detected channel is the $($UsedChannel.channelId) Channel." + exit 1 + } else { - # Office is either not on Semi-Annual channel or not on the latest version - # Exit code 1 indicates non-compliance - Write-Host "Not using Semi-Annual channel. Detected channel is the $($UsedChannel.channelId) Channel." - exit 1 + Write-Output "Non-compliant: on the Semi-Annual channel but behind. Installed $ReportedVersion, latest $($UsedChannel.latestversion)." + exit 1 } } # Error handling block - catches exceptions during registry reads or API calls catch { - # Capture and display the error message with script name for context + # The state could not be read. That is not evidence of non-compliance, and exiting 1 would send + # every device without network access to a remediation that also needs the network. $errMsg = $_.Exception.Message - Write-Error "Detect-OfficeUpdateChannel: Failed to detect Office update channel - $errMsg" + Write-Output "Cannot determine: $errMsg" if ($PSBoundParameters.ContainsKey('Verbose')) { Write-Verbose "Stack Trace: $($_.ScriptStackTrace)" if ($_.Exception.InnerException) { Write-Verbose "Inner Exception: $($_.Exception.InnerException.Message)" } } - # Exit with code 1 to indicate an error occurred - exit 1 + exit 0 } diff --git a/PSScriptAnalyzerSettings.psd1 b/PSScriptAnalyzerSettings.psd1 new file mode 100644 index 0000000..ff4d5dc --- /dev/null +++ b/PSScriptAnalyzerSettings.psd1 @@ -0,0 +1,13 @@ +@{ + # Errors and warnings fail CI. Information-level findings (trailing whitespace and the like) do not. + Severity = @('Error', 'Warning') + + ExcludeRules = @( + # These are interactive console scripts. Write-Host output for an operator is intended. + 'PSAvoidUsingWriteHost', + + # Style rule only. Get-GraphApiAllPages, Get-ProxySettings and Remove-ODataInjectionChars + # were already named this way before this branch, and other scripts may call them. + 'PSUseSingularNouns' + ) +} diff --git a/README.md b/README.md index 8367d74..a61a982 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ # Intune PowerShell Scripts -A comprehensive collection of PowerShell scripts for managing, troubleshooting, and reporting on Microsoft Intune deployments. These scripts provide detection, remediation, reporting, and management capabilities for Intune-managed devices and policies. +PowerShell scripts for managing, troubleshooting and reporting on Microsoft Intune deployments: detection and remediation scripts for Intune Remediations, Graph API reports, device troubleshooting and a few security settings. + +These scripts are tested with Pester against mocks. Nothing here has been run against a live tenant by the test suite. Read a script before you deploy it, run it with `-WhatIf` where it has one, and try it on a pilot device first. ## Table of Contents @@ -9,6 +11,7 @@ A comprehensive collection of PowerShell scripts for managing, troubleshooting, - [Installation](#installation) - [Project Structure](#project-structure) - [Quick Start](#quick-start) +- [How Intune runs the detection and remediation scripts](#how-intune-runs-the-detection-and-remediation-scripts) - [Script Categories](#script-categories) - [Detection & Remediation](#detection--remediation) - [Device Management](#device-management) @@ -20,45 +23,47 @@ A comprehensive collection of PowerShell scripts for managing, troubleshooting, - [Exit Codes](#exit-codes) - [Error Handling](#error-handling) - [Security Considerations](#security-considerations) +- [Testing](#testing) - [Contributing](#contributing) - [Script Index](#script-index) ## Overview -This repository contains production-ready PowerShell scripts designed for Microsoft Intune administrators. The scripts are organized into logical categories and follow PowerShell best practices, including: +The scripts are grouped by purpose and follow these rules: -- Comprehensive error handling -- Standardized exit codes -- Detailed logging and verbose output -- Input validation -- WhatIf support for modification scripts -- Progress indicators for long-running operations +- Error handling that ends in an exit code you can rely on. A script that could not finish does not exit 0. The one deliberate exception is a detection script that cannot read the state it checks (`Detect-OfficeUpdateChannel.ps1` without registry or network access): it exits 0 and says "Cannot determine", so Intune does not run a remediation that cannot succeed either. +- `-WhatIf` on every script that changes the machine. A `-WhatIf` run changes nothing and exits 0. +- Input validation on IDs, user names and paths. +- Reports that fail loudly. When a Graph request fails, the report row says so and the script exits 1. A blank value never stands for "the request failed". ## Prerequisites ### General Requirements - **Windows 10/11** or **Windows Server 2016+** -- **PowerShell 5.1** or later (PowerShell 7+ recommended) -- **Administrator privileges** (required for scripts that modify system settings) +- **Windows PowerShell 5.1** is the supported shell. The Graph reports and most troubleshooting scripts also run in PowerShell 7. `Start-MDMSync.ps1` needs Windows PowerShell 5.1 (Desktop edition): its Windows Runtime type does not load in PowerShell 7, and the script says so. +- **Administrator privileges** for scripts that change the machine or read protected logs (marked in the [Script Index](#script-index)) ### For Graph API Scripts -Scripts that interact with Microsoft Graph API require: +The Graph scripts use plain REST calls with a client secret and the shared `IntuneCommon` module. They do not need the Microsoft.Graph PowerShell SDK and they do not install it. + +You need an **Entra ID app registration** with these **Application** permissions (not Delegated), with **admin consent granted**. The scripts use the client credentials flow and the `.default` scope, so the permissions the app has consented are the permissions you get. -- **Microsoft.Graph PowerShell Module** (automatically installed if missing) -- **Entra ID App Registration** with the following Graph API permissions: - - `DeviceManagementManagedDevices.Read.All` - - `DeviceManagementConfiguration.Read.All` - - `DeviceManagementApps.Read.All` - - `Group.Read.All` (for group name resolution) +| Script | Application permissions it needs | +|---|---| +| `Get-IntuneDeviceDetails.ps1`, `Get-IntuneDeviceHealth.ps1` | `DeviceManagementManagedDevices.Read.All` | +| `Get-IntuneDeviceCompliance.ps1`, `Export-IntuneDeviceReport.ps1` | `DeviceManagementManagedDevices.Read.All`, `DeviceManagementConfiguration.Read.All` | +| `Get-IntunePolicyAssignments.ps1` | `DeviceManagementConfiguration.Read.All`, `Group.Read.All` (group names) | +| `Get-IntuneWin32AppDetails.ps1` | `DeviceManagementApps.Read.All` | +| `Get-IntuneAllAppsAssignmentDetails.ps1` | `DeviceManagementApps.Read.All`, `Group.Read.All` (group names) | ### App Registration Setup -1. Navigate to [Azure Portal](https://portal.azure.com) → **Entra ID** → **App registrations** +1. Go to [Azure Portal](https://portal.azure.com), then **Entra ID**, then **App registrations** 2. Create a new app registration or use an existing one -3. Create a **Client Secret** and note the value (it won't be shown again) -4. Grant the required API permissions listed above +3. Create a **Client Secret** and note the value (it is shown once) +4. Add the **Application** permissions from the table above and grant admin consent 5. Note the **Application (client) ID** and **Directory (tenant) ID** ## Installation @@ -70,13 +75,13 @@ Scripts that interact with Microsoft Graph API require: cd Intune_PowerShell_Scripts ``` -2. Import the common module (optional, but recommended): +2. The Graph scripts import `Common\IntuneCommon.psd1` themselves. You only import it by hand to use its functions in your own scripts: ```powershell - Import-Module .\Common\IntuneCommon.psm1 + Import-Module .\Common\IntuneCommon.psd1 ``` -3. Configure credentials using environment variables (recommended): +3. Give the Graph scripts their credentials. Environment variables are the simplest and keep the secret off the command line: ```powershell $env:INTUNE_APP_ID = "your-app-id" @@ -84,36 +89,46 @@ Scripts that interact with Microsoft Graph API require: $env:INTUNE_CLIENT_SECRET = "your-client-secret" ``` + Or pass them as parameters. `-ClientSecret` takes plain text and lands in shell history and process listings, so prefer `-ClientSecretSecure` with a `SecureString`: + + ```powershell + $secret = Read-Host -AsSecureString "Client secret" + .\Reporting\Get-IntuneDeviceDetails.ps1 -AppId "your-app-id" -TenantId "your-tenant-id" -ClientSecretSecure $secret + ``` + ## Project Structure ``` Intune_PowerShell_Scripts/ -├── Common/ -│ └── IntuneCommon.psm1 # Shared functions module -├── Detection/ -│ ├── Detect-MultipleIntuneMDMCert.ps1 # Detect duplicate MDM certificates -│ └── Detect-OfficeUpdateChannel.ps1 # Detect Office update channel -├── Remediation/ -│ ├── Repair-MultipleIntuneMDMCert.ps1 # Remove duplicate MDM certificates -│ └── Set-OfficeUpdateChannel.ps1 # Set Office to Semi-Annual channel -├── Reporting/ -│ ├── Export-IntuneDeviceReport.ps1 # Export comprehensive device reports -│ ├── Get-IntuneAllAppsAssignmentDetails.ps1 # Retrieve app assignment details -│ ├── Get-IntuneDeviceCompliance.ps1 # Retrieve device compliance status -│ ├── Get-IntuneDeviceDetails.ps1 # Retrieve device details -│ ├── Get-IntuneDeviceHealth.ps1 # Perform device health checks -│ ├── Get-IntunePolicyAssignments.ps1 # Retrieve policy assignments -│ └── Get-IntuneWin32AppDetails.ps1 # Retrieve Win32 app details -├── Security/ -│ ├── Disable-PrintSpoolerService.ps1 # Disable Print Spooler service -│ ├── Disable-SmartCardLogonEnforcement.ps1 # Disable smart card logon enforcement -│ ├── Enable-PrintSpoolerService.ps1 # Enable Print Spooler service -│ └── Enable-SmartCardLogonEnforcement.ps1 # Enable smart card logon enforcement -└── Troubleshooting/ - ├── Get-IntuneDeviceLogs.ps1 # Collect Intune-related logs - ├── Start-MDMSync.ps1 # Initiate MDM sync session - ├── Test-IntuneConnectivity.ps1 # Test connectivity to Intune endpoints - └── Test-IntuneEnrollment.ps1 # Test device enrollment status +|-- Common/ +| |-- IntuneCommon.psd1 # Module manifest +| `-- IntuneCommon.psm1 # Shared functions module +|-- Detection/ +| |-- Detect-MultipleIntuneMDMCert.ps1 # Detect duplicate MDM certificates +| `-- Detect-OfficeUpdateChannel.ps1 # Detect Office update channel +|-- Remediation/ +| |-- Repair-MultipleIntuneMDMCert.ps1 # Remove duplicate MDM certificates +| `-- Set-OfficeUpdateChannel.ps1 # Set Office to Semi-Annual channel +|-- Reporting/ +| |-- Export-IntuneDeviceReport.ps1 # Export comprehensive device reports +| |-- Get-IntuneAllAppsAssignmentDetails.ps1 # Retrieve app assignment details +| |-- Get-IntuneDeviceCompliance.ps1 # Retrieve device compliance status +| |-- Get-IntuneDeviceDetails.ps1 # Retrieve device details +| |-- Get-IntuneDeviceHealth.ps1 # Perform device health checks +| |-- Get-IntunePolicyAssignments.ps1 # Retrieve policy assignments +| `-- Get-IntuneWin32AppDetails.ps1 # Retrieve Win32 app details +|-- Security/ +| |-- Disable-PrintSpoolerService.ps1 # Disable Print Spooler service +| |-- Disable-SmartCardLogonEnforcement.ps1 # Disable smart card logon enforcement +| |-- Enable-PrintSpoolerService.ps1 # Enable Print Spooler service +| `-- Enable-SmartCardLogonEnforcement.ps1 # Enable smart card logon enforcement +|-- Troubleshooting/ +| |-- Get-IntuneDeviceLogs.ps1 # Collect Intune-related logs +| |-- Start-MDMSync.ps1 # Initiate MDM sync session +| |-- Test-IntuneConnectivity.ps1 # Test connectivity to Intune endpoints +| `-- Test-IntuneEnrollment.ps1 # Test device enrollment status +|-- Tests/ # Pester tests (see Testing) +`-- .github/workflows/ci.yml # PSScriptAnalyzer and Pester ``` ## Quick Start @@ -121,11 +136,8 @@ Intune_PowerShell_Scripts/ ### Example: Get Device Details ```powershell -.\Reporting\Get-IntuneDeviceDetails.ps1 ` - -AppId $env:INTUNE_APP_ID ` - -TenantId $env:INTUNE_TENANT_ID ` - -ClientSecret $env:INTUNE_CLIENT_SECRET ` - -ExportPath "C:\Reports\Devices.csv" +# INTUNE_APP_ID, INTUNE_TENANT_ID and INTUNE_CLIENT_SECRET are set +.\Reporting\Get-IntuneDeviceDetails.ps1 -ExportPath "C:\Reports\Devices.csv" ``` ### Example: Test Device Enrollment @@ -137,24 +149,30 @@ Intune_PowerShell_Scripts/ ### Example: Check Device Health ```powershell -.\Reporting\Get-IntuneDeviceHealth.ps1 ` - -AppId $env:INTUNE_APP_ID ` - -TenantId $env:INTUNE_TENANT_ID ` - -ClientSecret $env:INTUNE_CLIENT_SECRET ` - -ExportPath "C:\Reports\HealthReport.csv" +.\Reporting\Get-IntuneDeviceHealth.ps1 -ExportPath "C:\Reports\HealthReport.csv" ``` +## How Intune runs the detection and remediation scripts + +The `Detect-*` and `Repair-*` / `Set-*` scripts follow the contract of **Intune Remediations** (also called proactive remediations): + +- The **detection** script exits `0` when the device is fine and `1` when the remediation should run. +- The **remediation** script exits `0` on success and anything else on failure. +- In the Remediations script package, set **Run script in 64-bit PowerShell** to **Yes**. Intune runs scripts in 32-bit PowerShell by default. The Office scripts and the smart card scripts relaunch themselves in 64-bit PowerShell when they find they are in a 32-bit host, and forward `-WhatIf` and `-Verbose`, but the setting is the clean fix. + +These scripts are not for **custom compliance** policies. Custom compliance needs a script that prints JSON and a rules file, and these scripts print text and use exit codes. + +A device where the thing does not apply (no Office Click-to-Run) or cannot be checked (no network to Microsoft's release service) makes the Office detection script exit `0` with a message, so it does not go to remediation on every cycle. The message in the script output says which case it was. + ## Script Categories ### Detection & Remediation -Scripts designed for use in Intune compliance policies and remediation scripts. Detection scripts live in the `Detection\` directory; remediation scripts live in the `Remediation\` directory. +Detection scripts live in `Detection\`; remediation scripts live in `Remediation\`. -#### `Detect-MultipleIntuneMDMCert.ps1` — `Detection\` +#### `Detect-MultipleIntuneMDMCert.ps1` (Detection) -Detects multiple Intune MDM Device CA certificates in the Local Machine certificate store. Used as a detection script in Intune compliance policies. - -**Usage:** +Detects multiple Intune MDM Device CA certificates in the Local Machine certificate store. Use it as the detection script of a Remediation. ```powershell .\Detection\Detect-MultipleIntuneMDMCert.ps1 @@ -165,17 +183,11 @@ Detects multiple Intune MDM Device CA certificates in the Local Machine certific - `0`: No remediation needed (0 or 1 certificate found) - `1`: Remediation needed (more than 1 certificate found) or error occurred -**Parameters:** - -- None - --- -#### `Repair-MultipleIntuneMDMCert.ps1` — `Remediation\` +#### `Repair-MultipleIntuneMDMCert.ps1` (Remediation) -Remediation script that removes duplicate Intune MDM Device CA certificates, keeping only the most recent one. - -**Usage:** +Removes duplicate Intune MDM Device CA certificates, keeping the one with the newest `NotBefore` date. ```powershell .\Remediation\Repair-MultipleIntuneMDMCert.ps1 [-WhatIf] @@ -183,22 +195,18 @@ Remediation script that removes duplicate Intune MDM Device CA certificates, kee **Exit Codes:** -- `0`: Success (remediation completed or not needed) +- `0`: Success (duplicates removed, none found, or a `-WhatIf` run) - `1`: Error occurred -**Parameters:** - -- `-WhatIf`: Shows what would be done without making changes - **Requirements:** Administrator privileges ---- +**Note:** The older certificates are deleted without a backup, and the script does not check which certificate the enrollment currently references. It assumes the newest is the one in use. Run `-WhatIf` first and export the certificates you want to keep a copy of. -#### `Detect-OfficeUpdateChannel.ps1` — `Detection\` +--- -Verifies if Microsoft Office is using the Semi-Annual update channel and is on the latest version. Used as a detection script in Intune compliance policies. +#### `Detect-OfficeUpdateChannel.ps1` (Detection) -**Usage:** +Checks that Microsoft Office is on the Semi-Annual update channel and on the latest version of it. ```powershell .\Detection\Detect-OfficeUpdateChannel.ps1 @@ -206,22 +214,16 @@ Verifies if Microsoft Office is using the Semi-Annual update channel and is on t **Exit Codes:** -- `0`: Office is on Semi-Annual channel and latest version -- `1`: Office is not on Semi-Annual channel or not on latest version - -**Parameters:** +- `0`: Compliant, or not applicable (no Click-to-Run), or cannot determine (registry or Microsoft's release service not readable). The output says which. +- `1`: Not on the Semi-Annual channel, or on it but behind the latest version. The output says which. -- None - -**Requirements:** Office Click-to-Run installation +**Requirements:** None to run. Applies to Office Click-to-Run installations. --- -#### `Set-OfficeUpdateChannel.ps1` — `Remediation\` - -Remediation script that configures Microsoft Office to use the Semi-Annual update channel and triggers an update to the latest version. +#### `Set-OfficeUpdateChannel.ps1` (Remediation) -**Usage:** +Sets Office to the Semi-Annual channel and starts an update through `OfficeC2RClient.exe` in `Common Files\Microsoft Shared\ClickToRun`. ```powershell .\Remediation\Set-OfficeUpdateChannel.ps1 [-WhatIf] @@ -229,12 +231,8 @@ Remediation script that configures Microsoft Office to use the Semi-Annual updat **Exit Codes:** -- `0`: Success (Office configured and updated) -- `1`: Error occurred - -**Parameters:** - -- `-WhatIf`: Shows what would be done without making changes +- `0`: Success, already compliant, not applicable (no Click-to-Run), or a `-WhatIf` run +- `1`: Error occurred, including a missing updater **Requirements:** Administrator privileges, Office Click-to-Run installation @@ -242,126 +240,91 @@ Remediation script that configures Microsoft Office to use the Semi-Annual updat ### Device Management -Scripts for managing and monitoring Intune-enrolled devices. These scripts live in either the `Reporting\` or `Troubleshooting\` directory depending on function. - -#### `Get-IntuneDeviceDetails.ps1` — `Reporting\` +#### `Get-IntuneDeviceDetails.ps1` (Reporting) -Retrieves comprehensive information about Intune-managed devices including enrollment details, hardware information, compliance state, and management agent. - -**Usage:** +Retrieves information about Intune-managed devices: enrollment details, hardware, compliance state and management agent. All result pages are read. ```powershell # Get all devices -.\Reporting\Get-IntuneDeviceDetails.ps1 -AppId 'app-id' -TenantId 'tenant-id' -ClientSecret 'secret' +.\Reporting\Get-IntuneDeviceDetails.ps1 # Get specific device -.\Reporting\Get-IntuneDeviceDetails.ps1 -DeviceId 'device-guid' -AppId 'app-id' -TenantId 'tenant-id' -ClientSecret 'secret' - -# Search by device name -.\Reporting\Get-IntuneDeviceDetails.ps1 -DeviceName 'LAPTOP-*' -ExportPath 'C:\Reports\Devices.csv' +.\Reporting\Get-IntuneDeviceDetails.ps1 -DeviceId 'device-guid' -# Export to CSV -.\Reporting\Get-IntuneDeviceDetails.ps1 -ExportPath 'C:\Reports\Devices.csv' -AppId 'app-id' -TenantId 'tenant-id' -ClientSecret 'secret' +# Search by device name (substring match) +.\Reporting\Get-IntuneDeviceDetails.ps1 -DeviceName 'LAPTOP-01' -ExportPath 'C:\Reports\Devices.csv' ``` **Parameters:** - `-DeviceId`: Specific device ID to query -- `-DeviceName`: Device name filter (supports wildcards) +- `-DeviceName`: Substring of the device name. Graph `contains()` does not expand wildcards, so `*` and `%` are removed from the value, not expanded. - `-ExportPath`: Path to export CSV file -- `-AppId`: Entra ID Application ID (or use environment variable) -- `-TenantId`: Entra ID Tenant ID (or use environment variable) -- `-ClientSecret`: Entra ID Client Secret (or use environment variable) +- `-AppId`, `-TenantId`, `-ClientSecretSecure` (or `-ClientSecret`): credentials, or use the environment variables --- -#### `Get-IntuneDeviceCompliance.ps1` — `Reporting\` +#### `Get-IntuneDeviceCompliance.ps1` (Reporting) -Retrieves compliance status for Intune-managed devices, including compliance policy assignments and compliance state. - -**Usage:** +Retrieves compliance status for devices. For each device it reads that device's own compliance policy states, so `CompliancePolicies` reads like `Baseline (compliant); BitLocker (nonCompliant)` and `NonCompliantPolicies` lists the ones that are not compliant. Per-setting non-compliance reasons are not retrieved. ```powershell -# Get compliance for all devices -.\Reporting\Get-IntuneDeviceCompliance.ps1 -AppId 'app-id' -TenantId 'tenant-id' -ClientSecret 'secret' - -# Get compliance for specific device +.\Reporting\Get-IntuneDeviceCompliance.ps1 .\Reporting\Get-IntuneDeviceCompliance.ps1 -DeviceId 'device-guid' -ExportPath 'C:\Reports\Compliance.csv' - -# Get compliance for user's devices .\Reporting\Get-IntuneDeviceCompliance.ps1 -UserPrincipalName 'user@domain.com' -ExportPath 'C:\Reports\UserCompliance.csv' ``` **Parameters:** -- `-DeviceId`: Specific device ID to query -- `-UserPrincipalName`: User principal name to filter devices +- `-DeviceId`, `-UserPrincipalName`: limit the report to one device or one user's devices +- `-SkipPolicyStates`: skip the per-device policy request. That is one request per device; skip it on a large tenant. - `-ExportPath`: Path to export CSV file -- `-AppId`: Entra ID Application ID (or use environment variable) -- `-TenantId`: Entra ID Tenant ID (or use environment variable) -- `-ClientSecret`: Entra ID Client Secret (or use environment variable) +- Credentials as above ---- +A device whose policy states cannot be read gets a `CollectionError` value and the script exits `1`. -#### `Get-IntuneDeviceHealth.ps1` — `Reporting\` +--- -Performs comprehensive health checks on Intune-managed devices including enrollment status, sync status, compliance state, management agent, and storage space. +#### `Get-IntuneDeviceHealth.ps1` (Reporting) -**Usage:** +Scores each device out of 100 from enrollment, last sync, compliance state, management agent, operating system and storage. The weights are fixed values documented in the script header and are a rule of thumb, not a Microsoft measure. ```powershell -# Check health for all devices -.\Reporting\Get-IntuneDeviceHealth.ps1 -AppId 'app-id' -TenantId 'tenant-id' -ClientSecret 'secret' - -# Check health for specific device +.\Reporting\Get-IntuneDeviceHealth.ps1 .\Reporting\Get-IntuneDeviceHealth.ps1 -DeviceId 'device-guid' -ExportPath 'C:\Reports\HealthReport.csv' ``` -**Parameters:** +**Health check factors:** -- `-DeviceId`: Specific device ID to query -- `-ExportPath`: Path to export CSV file -- `-AppId`: Entra ID Application ID (or use environment variable) -- `-TenantId`: Entra ID Tenant ID (or use environment variable) -- `-ClientSecret`: Entra ID Client Secret (or use environment variable) - -**Health Check Factors:** - -- Enrollment status and age -- Last sync time +- Enrolled or not +- Last sync time (a device that has never synced is reported as "Never Synced") - Compliance state -- Management agent type -- Operating system version +- Management agent (any Graph `managementAgentType` value is fine; only `unknown` or missing is flagged) +- Operating system - Storage space (if available) --- -#### `Test-IntuneEnrollment.ps1` — `Troubleshooting\` - -Tests if a device is properly enrolled in Intune by checking enrollment status, MDM authority, enrollment date, and Intune Management Extension service. +#### `Test-IntuneEnrollment.ps1` (Troubleshooting) -**Usage:** +Checks whether the device is enrolled in Intune. It reads the enrollment records under `HKLM:\SOFTWARE\Microsoft\Enrollments`, looks for one with ProviderID `MS DM Server` and EnrollmentState `1`, and reports the user, the Intune device ID, the first sync time and the state of the Intune Management Extension service. ```powershell -.\Troubleshooting\Test-IntuneEnrollment.ps1 [-Verbose] +.\Troubleshooting\Test-IntuneEnrollment.ps1 ``` **Exit Codes:** -- `0`: Device is properly enrolled -- `1`: Device is not enrolled or enrollment issues detected - -**Parameters:** +- `0`: Enrolled in Intune +- `1`: Not enrolled, enrollment state is not "enrolled", or an error occurred -- `-Verbose`: Display detailed enrollment information +The script was checked against a device with no Intune enrollment and against mocked enrollments. It has not been run on an enrolled device. --- -#### `Start-MDMSync.ps1` — `Troubleshooting\` - -Initiates an MDM sync session between the device and Intune using Windows Management APIs. +#### `Start-MDMSync.ps1` (Troubleshooting) -**Usage:** +Starts an MDM sync session between the device and Intune with the Windows Management API and waits for it to finish. ```powershell # Default timeout (60 seconds) @@ -373,312 +336,247 @@ Initiates an MDM sync session between the device and Intune using Windows Manage **Exit Codes:** -- `0`: Sync completed successfully -- `1`: Sync failed or ended with error state -- `2`: Sync timeout (didn't complete within timeout period) +- `0`: Sync completed with no error +- `1`: Session could not be created, or it completed with an extended error code, or an error occurred +- `2`: Sync did not complete within the timeout **Parameters:** - `-TimeoutSeconds`: Maximum time in seconds to wait for sync (default: 60) - `-CheckIntervalSeconds`: Interval in seconds between status checks (default: 5) -**Requirements:** Windows 10/11 with MDM enrollment +**Requirements:** Windows PowerShell 5.1 (Desktop edition), Windows 10/11 with MDM enrollment. PowerShell 7 is refused with a clear message. --- ### Reporting & Analysis -Scripts for generating reports and analyzing Intune deployments. These scripts live in the `Reporting\` directory. +#### `Get-IntuneAllAppsAssignmentDetails.ps1` (Reporting) -#### `Get-IntuneAllAppsAssignmentDetails.ps1` — `Reporting\` - -Retrieves all applications published in Microsoft Intune and exports their assignment details to a CSV file. - -**Usage:** +Retrieves all applications published in Intune and exports their assignment details to a CSV file. Each assignment is a row with the intent (`Assignment`), the group (`Group`) and what it targets (`TargetType`: `All Users`, `All Devices`, `Group` or `Excluded group`). An excluded group is a group the app is not deployed to. Apps with no assignment get one `Not Assigned` row. ```powershell -.\Reporting\Get-IntuneAllAppsAssignmentDetails.ps1 ` - -AppId 'app-id' ` - -TenantId 'tenant-id' ` - -ClientSecret 'secret' ` - -ExportCSVpath 'C:\Reports\AppAssignments.csv' +.\Reporting\Get-IntuneAllAppsAssignmentDetails.ps1 -ExportCSVpath 'C:\Reports\AppAssignments.csv' ``` **Parameters:** -- `-ExportCSVpath`: Path to export CSV file (default: `C:\Temp\Get-IntuneAllAppsAssignmentDetails.csv`) -- `-AppId`: Entra ID Application ID (or use environment variable) -- `-TenantId`: Entra ID Tenant ID (or use environment variable) -- `-ClientSecret`: Entra ID Client Secret (or use environment variable) +- `-ExportCSVpath`: Path to export CSV file (default: `$env:TEMP\Get-IntuneAllAppsAssignmentDetails.csv`) +- Credentials as above ---- +The query uses the Graph beta endpoint (`$expand=Assignments,Category,Version`) and reads every page. -#### `Get-IntunePolicyAssignments.ps1` — `Reporting\` +--- -Retrieves all Intune policy assignments including configuration profiles and compliance policies with their target groups. +#### `Get-IntunePolicyAssignments.ps1` (Reporting) -**Usage:** +Retrieves configuration profile and compliance policy assignments with their targets. A policy with no assignments appears as a row with `TargetType` `None`. A policy whose assignments could not be read appears as `TargetType` `Error` and the script exits `1`. ```powershell -# Get all policy assignments -.\Reporting\Get-IntunePolicyAssignments.ps1 -AppId 'app-id' -TenantId 'tenant-id' -ClientSecret 'secret' - -# Get only configuration profiles +.\Reporting\Get-IntunePolicyAssignments.ps1 .\Reporting\Get-IntunePolicyAssignments.ps1 -PolicyType "Configuration" -ExportPath 'C:\Reports\ConfigProfiles.csv' - -# Get only compliance policies .\Reporting\Get-IntunePolicyAssignments.ps1 -PolicyType "Compliance" -ExportPath 'C:\Reports\CompliancePolicies.csv' ``` **Parameters:** -- `-PolicyType`: Type of policies to retrieve ("All", "Configuration", or "Compliance") (default: "All") +- `-PolicyType`: `All`, `Configuration` or `Compliance` (default: `All`) - `-ExportPath`: Path to export CSV file -- `-AppId`: Entra ID Application ID (or use environment variable) -- `-TenantId`: Entra ID Tenant ID (or use environment variable) -- `-ClientSecret`: Entra ID Client Secret (or use environment variable) +- Credentials as above --- -#### `Get-IntuneWin32AppDetails.ps1` — `Reporting\` +#### `Get-IntuneWin32AppDetails.ps1` (Reporting) -Retrieves detailed information about Win32 app deployments including installation status, assignment details, and device installation status. - -**Usage:** +Retrieves Win32 app details and assignments. With `-DeviceId` it adds the install state Intune reports for that device (`mobileApps/{id}/deviceStatuses`, which exists only in the Graph beta endpoint): `installed`, `failed`, `notInstalled`, `pendingInstall` and so on, or `NotReported` when Intune has no row for that app on that device. That is one extra request per app. ```powershell -# Get all Win32 apps -.\Reporting\Get-IntuneWin32AppDetails.ps1 -AppId 'app-id' -TenantId 'tenant-id' -ClientSecret 'secret' - -# Get specific app +.\Reporting\Get-IntuneWin32AppDetails.ps1 .\Reporting\Get-IntuneWin32AppDetails.ps1 -IntuneAppId 'app-guid' -ExportPath 'C:\Reports\AppDetails.csv' - -# Get app with device installation status .\Reporting\Get-IntuneWin32AppDetails.ps1 -IntuneAppId 'app-guid' -DeviceId 'device-guid' -ExportPath 'C:\Reports\AppStatus.csv' ``` **Parameters:** - `-IntuneAppId`: Specific Win32 app ID to query -- `-DeviceId`: Device ID to check installation status +- `-DeviceId`: Device ID to read install status for - `-ExportPath`: Path to export CSV file -- `-AppId`: Entra ID Application ID (or use environment variable) -- `-TenantId`: Entra ID Tenant ID (or use environment variable) -- `-ClientSecret`: Entra ID Client Secret (or use environment variable) +- Credentials as above ---- +An app whose assignments or device status could not be read gets an `AssignmentError` or `DeviceStatusError` value, and the script exits `1`. Device status has been exercised only with mocks. -#### `Export-IntuneDeviceReport.ps1` — `Reporting\` +--- -Exports comprehensive device information to CSV or JSON format including device details, compliance status, policy assignments, and configuration profile states. +#### `Export-IntuneDeviceReport.ps1` (Reporting) -**Usage:** +Exports device information to CSV or JSON, with each device's compliance policy states and configuration profile states. ```powershell # Export all devices to CSV -.\Reporting\Export-IntuneDeviceReport.ps1 -AppId 'app-id' -TenantId 'tenant-id' -ClientSecret 'secret' +.\Reporting\Export-IntuneDeviceReport.ps1 -# Export specific device to JSON -.\Reporting\Export-IntuneDeviceReport.ps1 ` - -DeviceId 'device-guid' ` - -Format 'JSON' ` - -OutputPath 'C:\Reports\DeviceReport.json' ` - -AppId 'app-id' ` - -TenantId 'tenant-id' ` - -ClientSecret 'secret' +# Export a specific device to JSON +.\Reporting\Export-IntuneDeviceReport.ps1 -DeviceId 'device-guid' -Format 'JSON' -OutputPath 'C:\Reports\DeviceReport.json' ``` **Parameters:** - `-DeviceId`: Specific device ID to export -- `-Format`: Export format ("CSV" or "JSON") (default: "CSV") -- `-OutputPath`: Path to export file (default: timestamped file in `$env:TEMP\IntuneReports`) -- `-AppId`: Entra ID Application ID (or use environment variable) -- `-TenantId`: Entra ID Tenant ID (or use environment variable) -- `-ClientSecret`: Entra ID Client Secret (or use environment variable) +- `-Format`: `CSV` or `JSON` (default: `CSV`) +- `-OutputPath`: Path to export file (default: a timestamped file in `$env:TEMP`) +- Credentials as above ---- +A device whose states could not be read gets a `CollectionErrors` value; the file is still written and the script exits `1`. -#### `Get-IntuneDeviceLogs.ps1` — `Troubleshooting\` +--- -Collects Intune-related logs from the device including Intune Management Extension logs, MDM enrollment registry information, and Windows Event Logs. +#### `Get-IntuneDeviceLogs.ps1` (Troubleshooting) -**Usage:** +Collects Intune Management Extension logs, MDM logs, the Enrollments registry export and, on request, Windows event logs. ```powershell -# Collect logs to default location .\Troubleshooting\Get-IntuneDeviceLogs.ps1 - -# Collect logs with Event Logs to custom location .\Troubleshooting\Get-IntuneDeviceLogs.ps1 -OutputPath 'C:\Logs\Intune' -IncludeEventLogs ``` **Parameters:** - `-OutputPath`: Path to save collected logs (default: timestamped folder in `$env:TEMP\IntuneLogs`) -- `-IncludeEventLogs`: Include Windows Event Logs in collection +- `-IncludeEventLogs`: Include the DeviceManagement and User Device Registration event logs -**Requirements:** Administrator privileges +**Exit Codes:** -**Collected Logs:** +- `0`: Every collection that was attempted succeeded +- `1`: Any collection failed, nothing was collected, or an error occurred + +**Requirements:** Administrator privileges -- Intune Management Extension logs -- MDM enrollment registry information -- Windows Event Logs (if `-IncludeEventLogs` is specified) +**Note:** The logs and the registry export contain device and user identifiers. When the script creates the output folder it limits access to SYSTEM and Administrators. A folder that already exists keeps its permissions. --- ### Service Management -Scripts for managing Windows services related to Intune and security. These scripts live in the `Security\` directory. +These scripts live in `Security\`. -#### `Disable-PrintSpoolerService.ps1` — `Security\` +#### `Disable-PrintSpoolerService.ps1` (Security) -Disables the Print Spooler service to mitigate PrintNightmare vulnerabilities. - -**Usage:** +Stops the Print Spooler service and sets it to Disabled, to mitigate PrintNightmare-class vulnerabilities. ```powershell .\Security\Disable-PrintSpoolerService.ps1 [-WhatIf] ``` -**Exit Codes:** - -- `0`: Success (service disabled) -- `1`: Error occurred - -**Parameters:** - -- `-WhatIf`: Shows what would be done without making changes +**Exit Codes:** `0` service disabled or `-WhatIf` run, `1` error **Requirements:** Administrator privileges -**Note:** This will disable printing functionality on the device. +**Note:** Printing stops working. The script does not use `-Force`, so if a running service depends on the spooler, the stop fails and the script exits `1` with a message that names it. --- -#### `Enable-PrintSpoolerService.ps1` — `Security\` +#### `Enable-PrintSpoolerService.ps1` (Security) -Enables the Print Spooler service and sets it to start automatically. - -**Usage:** +Sets the Print Spooler service to Automatic and starts it. ```powershell .\Security\Enable-PrintSpoolerService.ps1 [-WhatIf] ``` -**Exit Codes:** - -- `0`: Success (service enabled) -- `1`: Error occurred - -**Parameters:** - -- `-WhatIf`: Shows what would be done without making changes +**Exit Codes:** `0` service enabled or `-WhatIf` run, `1` error **Requirements:** Administrator privileges --- -#### `Disable-SmartCardLogonEnforcement.ps1` — `Security\` - -Disables smart card logon enforcement by modifying registry keys and disabling the Smart Card Policy Service. +#### `Disable-SmartCardLogonEnforcement.ps1` (Security) -**Usage:** +Sets `scforceoption` and `ScRemoveOption` to 0 and sets the Smart Card Policy Service (`SCPolicySvc`) to Disabled. Password logon works again and the workstation no longer locks when a card is removed. This is also the way back from the Enable script on a device that can still reach Intune. ```powershell -.\Security\Disable-SmartCardLogonEnforcement.ps1 [-WhatIf] +.\Security\Disable-SmartCardLogonEnforcement.ps1 [-WhatIf] [-KeepLogs] ``` -**Exit Codes:** - -- `0`: Success (smart card enforcement disabled) -- `1`: Error occurred - -**Parameters:** - -- `-WhatIf`: Shows what would be done without making changes +**Exit Codes:** `0` all values written and read back, or `-WhatIf` run; `1` a write or its read-back failed **Requirements:** Administrator privileges -**Note:** This allows password-based logon and prevents auto-lock on smart card removal. +**Log:** `%ProgramData%\Microsoft\IntuneManagementExtension\Logs\win32-Disable_SmartCardLogon_Enforcement.log`. The log is always kept. `-KeepLogs` is accepted for old callers and does nothing. --- -#### `Enable-SmartCardLogonEnforcement.ps1` — `Security\` +#### `Enable-SmartCardLogonEnforcement.ps1` (Security) -Enables smart card logon enforcement by modifying registry keys and enabling the Smart Card Policy Service. +> **Lockout warning.** This sets "Interactive logon: Require smart card". Password logon stops working for every account on the device, **including the local administrator**. A device with no smart card reader, no card or no certificate-based logon set up can be locked out for good. -**Usage:** +Sets `scforceoption` and `ScRemoveOption` to 1 and sets `SCPolicySvc` to Automatic. ```powershell -.\Security\Enable-SmartCardLogonEnforcement.ps1 [-WhatIf] +.\Security\Enable-SmartCardLogonEnforcement.ps1 [-WhatIf] [-Force] ``` -**Exit Codes:** - -- `0`: Success (smart card enforcement enabled) -- `1`: Error occurred +**Safeguard:** before it writes anything the script checks that `SCPolicySvc` exists and that at least one smart card reader is present and healthy. If not, it exits `1` and changes nothing. The check cannot see cards or logon certificates, so confirm those yourself. Intune cannot pass parameters to a remediation or platform script, so on managed devices this check is the safeguard. `-Force` skips it and is for a supervised run only. -**Parameters:** +**Recovery from a lockout:** boot to Windows Recovery, load the device's `SOFTWARE` hive in `regedit` and set `HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\scforceoption` to `0`. Or run `Disable-SmartCardLogonEnforcement.ps1` through Intune on a device that can still check in. -- `-WhatIf`: Shows what would be done without making changes +**Exit Codes:** `0` all values written and read back, or `-WhatIf` run; `1` preflight refused, a write failed or a read-back did not match **Requirements:** Administrator privileges -**Note:** This enforces smart card authentication and enables auto-lock on smart card removal. +**Log:** `%ProgramData%\Microsoft\IntuneManagementExtension\Logs\win32-Enable_SmartCardLogon_Enforcement.log`, always kept. --- ### Connectivity & Testing -Scripts for testing connectivity and enrollment status. These scripts live in the `Troubleshooting\` directory. - -#### `Test-IntuneConnectivity.ps1` — `Troubleshooting\` +#### `Test-IntuneConnectivity.ps1` (Troubleshooting) -Tests connectivity to Microsoft Intune and Microsoft 365 endpoints, displays network configuration information, and exports results to CSV. - -**Usage:** +Tests connectivity to the mandatory Microsoft Intune (MEM) and Microsoft 365 Common endpoints, shows the network configuration and exports the results as **JSON**. ```powershell -# Test connectivity .\Troubleshooting\Test-IntuneConnectivity.ps1 - -# Test with export -.\Troubleshooting\Test-IntuneConnectivity.ps1 -ExportPath 'C:\Reports\Connectivity.csv' +.\Troubleshooting\Test-IntuneConnectivity.ps1 -ExportPath 'C:\Reports\Connectivity.json' ``` **Parameters:** -- `-ExportPath`: Path to export CSV file with test results +- `-ExportPath`: Path to export the results as a JSON file +- `-IncludeUnlistedEndpoints`: Also test endpoint sets that are not in the script's built-in category tables. By default they are listed as not tested. + +**How it decides:** + +- A host that answers with any HTTP status counts as reachable. A timeout, DNS failure or refused connection counts as a failure. +- A host that publishes ports 80 and 443 is tried on https, then http. +- Wildcard-only entries (for example `*.microsoftonline.com`) and UDP-only entries (NTP) cannot be tested over HTTP and are reported as skipped. +- If either endpoint list cannot be retrieved, the test fails. -**Tested Endpoints:** +**Exit Codes:** `0` all tested mandatory endpoints reachable, `1` otherwise -- Microsoft 365 Common endpoints (authentication, identity) -- Intune/MEM endpoints (device management, enrollment) +**Known quirk:** a few hosts in Microsoft's published list have no address record or do not complete TLS (at the last live run: `activity.windows.com`, `adl.windows.com` and `windowsphone.com`). They show as failed. --- ## Common Module -### `IntuneCommon.psm1` — `Common\` +### `IntuneCommon.psd1` / `IntuneCommon.psm1` (Common) -A PowerShell module containing shared functions used across multiple scripts: +A PowerShell module with the helpers the Graph scripts share: -- **`Invoke-GraphApiWithRetry`**: Invokes Graph API requests with automatic retry logic and exponential backoff -- **`Get-GraphAccessToken`**: Retrieves OAuth2 access token for Microsoft Graph API -- **`Test-GuidFormat`**: Validates GUID format -- **`Test-EmailFormat`**: Validates email address format -- **`Remove-ODataInjectionChars`**: Sanitizes input for OData queries - -**Usage:** +- **`Get-IntuneCredential`**: resolves app ID, tenant ID and secret from parameters or the `INTUNE_*` environment variables, rejects placeholders, returns the secret as a `SecureString` +- **`Get-GraphAccessToken`**: requests an OAuth2 token (secret as `SecureString` or plain string) +- **`Get-IntuneGraphHeaders`**: token plus ready-to-use request headers +- **`Invoke-GraphApiWithRetry`**: Graph request with retry and exponential backoff, honouring `Retry-After` on a 429 +- **`Get-GraphApiAllPages`**: follows `@odata.nextLink` and returns every item +- **`ConvertTo-ODataStringLiteral`**: quotes a value for a `$filter` and doubles single quotes. Pass the finished filter through `[uri]::EscapeDataString`. +- **`Remove-ODataInjectionChars`**, **`Test-ODataFilterInput`**: escape a value by doubling quotes (they used to delete quotes) +- **`Protect-CsvValue`**, **`ConvertTo-SafeCsvRecord`**: prefix a leading `=`, `+`, `-`, `@`, tab or carriage return with an apostrophe so a spreadsheet does not run a device name as a formula. A string that starts with `-` gets the apostrophe too. +- **`Test-GuidFormat`**, **`Test-EmailFormat`**: format checks +- **`ConvertTo-Array`**, **`Get-IntuneLogPath`**, **`Write-StandardError`**: small utilities ```powershell -Import-Module .\Common\IntuneCommon.psm1 +Import-Module .\Common\IntuneCommon.psd1 ``` -The module is automatically used by scripts that require Graph API access. You can also use it directly in your own scripts. - --- ## Usage Examples @@ -686,35 +584,23 @@ The module is automatically used by scripts that require Graph API access. You c ### Example 1: Generate Comprehensive Device Report ```powershell -# Export all devices to CSV with full details .\Reporting\Export-IntuneDeviceReport.ps1 ` - -AppId $env:INTUNE_APP_ID ` - -TenantId $env:INTUNE_TENANT_ID ` - -ClientSecret $env:INTUNE_CLIENT_SECRET ` -OutputPath "C:\Reports\AllDevices_$(Get-Date -Format 'yyyyMMdd').csv" ``` ### Example 2: Check Compliance for Specific User ```powershell -# Get compliance status for all devices owned by a user .\Reporting\Get-IntuneDeviceCompliance.ps1 ` -UserPrincipalName "john.doe@contoso.com" ` - -ExportPath "C:\Reports\JohnDoe_Compliance.csv" ` - -AppId $env:INTUNE_APP_ID ` - -TenantId $env:INTUNE_TENANT_ID ` - -ClientSecret $env:INTUNE_CLIENT_SECRET + -ExportPath "C:\Reports\JohnDoe_Compliance.csv" ``` ### Example 3: Monitor Device Health ```powershell -# Check health for all devices and export results .\Reporting\Get-IntuneDeviceHealth.ps1 ` - -ExportPath "C:\Reports\DeviceHealth_$(Get-Date -Format 'yyyyMMdd').csv" ` - -AppId $env:INTUNE_APP_ID ` - -TenantId $env:INTUNE_TENANT_ID ` - -ClientSecret $env:INTUNE_CLIENT_SECRET + -ExportPath "C:\Reports\DeviceHealth_$(Get-Date -Format 'yyyyMMdd').csv" ``` ### Example 4: Remediate Office Update Channel @@ -732,96 +618,87 @@ if ($LASTEXITCODE -eq 1) { ### Example 5: Collect Logs for Troubleshooting ```powershell -# Collect all Intune-related logs .\Troubleshooting\Get-IntuneDeviceLogs.ps1 ` -OutputPath "C:\Logs\Intune_$(Get-Date -Format 'yyyyMMdd_HHmmss')" ` -IncludeEventLogs ``` +(The Graph examples assume the `INTUNE_*` environment variables are set.) + --- ## Exit Codes -All scripts follow standard exit code conventions: - | Exit Code | Meaning | |-----------|---------| -| `0` | Success / No action needed | -| `1` | Failure / Action needed / Error occurred | -| `2` | Timeout or specific error condition (where applicable) | +| `0` | Success, nothing to do, or a `-WhatIf` run | +| `1` | Failure, action needed (detection scripts), or an incomplete report | +| `2` | Timeout (`Start-MDMSync.ps1`) | ### Exit Code Usage -- **Detection scripts**: `0` = compliant, `1` = non-compliant or error -- **Remediation scripts**: `0` = success, `1` = error -- **Reporting scripts**: `0` = success, `1` = error -- **Management scripts**: `0` = success, `1` = error, `2` = timeout +- **Detection scripts**: `0` = compliant, not applicable or cannot determine; `1` = run the remediation +- **Remediation scripts**: `0` = success, `1` = failure +- **Reporting scripts**: `0` = complete report, `1` = error or incomplete report (rows marked with an error value) +- **Troubleshooting and security scripts**: `0` = success, `1` = failure; `Start-MDMSync.ps1` also uses `2` for a timeout --- ## Error Handling -All scripts include comprehensive error handling: - -- **Try-catch blocks** for exception handling -- **Standardized error messages** with script name prefixes -- **Verbose output** for debugging (use `-Verbose` parameter) -- **Stack traces** in verbose mode -- **Null response handling** for API calls -- **Input validation** for parameters -- **Progress indicators** for long-running operations - -### Error Message Format - -Error messages follow a consistent format: +- **Try-catch blocks** around the work, with a non-zero exit code on failure +- **Error messages** with the script name as a prefix +- **Verbose output** for debugging (use `-Verbose`) +- **Report rows that carry the error** for Graph reports, not blank values +- **Input validation** for GUIDs, user names and paths ```text ScriptName: Failed to perform action - Error details ``` -### Verbose Output - -Use the `-Verbose` parameter to get detailed information: - -```powershell -.\Reporting\Get-IntuneDeviceDetails.ps1 -DeviceId 'guid' -Verbose -``` - --- ## Security Considerations ### Credentials -- **Never hardcode credentials** in scripts -- Use **environment variables** or **parameters** for sensitive information -- Consider using **Azure Key Vault** for production environments -- **Rotate client secrets** regularly +- Never hardcode credentials in scripts +- Use the **environment variables** or `-ClientSecretSecure`. `-ClientSecret` with a literal value is visible in shell history, process listings and transcripts. +- Use a vault such as Azure Key Vault to hold the secret and read it into the environment variable at run time +- Rotate client secrets regularly ### Permissions -- Scripts that modify system settings require **administrator privileges** -- Graph API scripts require **appropriate API permissions** in Entra ID -- Use **principle of least privilege** when assigning permissions +- The Graph scripts use **Application** permissions with admin consent. Grant only the ones in the [permissions table](#for-graph-api-scripts). +- Scripts that change the machine need administrator privileges + +### Registry and service changes -### Registry Modifications +- Some scripts change registry keys or services. Review them, use `-WhatIf` and test on a pilot device first. +- `Enable-SmartCardLogonEnforcement.ps1` can lock every user out of a device. Read its section. +- `Repair-MultipleIntuneMDMCert.ps1` deletes certificates without a backup. -- Some scripts modify registry keys -- **Always review changes** before deployment -- **Test in non-production** environments first -- **Backup registry** before making changes +### Network Security -### Service Management Security +- The scripts talk to Microsoft Graph and the Microsoft sign-in service over HTTPS +- Use `Test-IntuneConnectivity.ps1` to verify the network path -- Service management scripts can **impact system functionality** -- Use `-WhatIf` parameter to preview changes -- **Test thoroughly** before deploying to production +### Spreadsheets -### Network Security +- CSV output is formula-safe: a leading `=`, `+`, `-` or `@` is prefixed with an apostrophe + +--- + +## Testing + +Tests are Pester 5 files in `Tests\`. They mock the registry, services, certificate store, files and every network call, so they never contact a tenant and never change the machine. The tests that run an elevated script need an elevated shell and skip themselves otherwise. + +```powershell +Install-Module Pester -RequiredVersion 5.9.1 -Scope CurrentUser +Invoke-Pester -Path .\Tests +``` -- Scripts communicate with Microsoft Graph API over HTTPS -- Ensure **firewall rules** allow access to Graph API endpoints -- Use **Test-IntuneConnectivity.ps1** to verify network connectivity +The GitHub Actions workflow in `.github\workflows\ci.yml` runs PSScriptAnalyzer (settings in `PSScriptAnalyzerSettings.psd1`) and Pester on every push and pull request. --- @@ -829,34 +706,13 @@ Use the `-Verbose` parameter to get detailed information: When contributing to this repository: -1. **Follow PowerShell best practices**: - - Use approved verbs (Get, Set, Test, Start, etc.) - - Follow verb-noun naming convention - - Include comprehensive help documentation - -2. **Code quality**: - - Include comprehensive header documentation - - Add inline comments explaining functionality - - Implement proper error handling - - Use appropriate exit codes - - Add input validation - -3. **Testing**: - - Test scripts thoroughly before committing - - Test with `-WhatIf` parameter for modification scripts - - Test error scenarios - - Verify exit codes - -4. **Documentation**: - - Update README.md with new scripts - - Include usage examples - - Document all parameters - - Document exit codes - -5. **Common functions**: - - Use `IntuneCommon.psm1` for shared functionality - - Add new common functions when appropriate - - Keep functions focused and reusable +1. **Follow PowerShell best practices**: approved verbs, verb-noun names, help in the script header. +2. **Make exit codes truthful**: a script that did not finish must not exit 0. No `-ErrorAction SilentlyContinue` on a write you depend on. +3. **Give every change a real `-WhatIf`**: nothing is created, written or deleted, and the exit code is 0. +4. **Add a Pester test** for each bug you fix, in the style of the existing tests (mock every state-changing cmdlet). +5. **Run PSScriptAnalyzer** with the repository settings and keep it clean. +6. **Update this README** and `CHANGELOG.md`. +7. **Use `IntuneCommon.psd1`** for shared Graph functionality. --- @@ -872,18 +728,18 @@ When contributing to this repository: | `Get-IntuneDeviceCompliance.ps1` | `Reporting\` | Reporting | No | Yes | Retrieves device compliance status | | `Get-IntuneDeviceHealth.ps1` | `Reporting\` | Reporting | No | Yes | Performs device health checks | | `Test-IntuneEnrollment.ps1` | `Troubleshooting\` | Testing | No | No | Tests device enrollment status | -| `Start-MDMSync.ps1` | `Troubleshooting\` | Management | No | No | Initiates MDM sync session | +| `Start-MDMSync.ps1` | `Troubleshooting\` | Management | No | No | Initiates MDM sync session (Windows PowerShell 5.1) | | `Get-IntuneAllAppsAssignmentDetails.ps1` | `Reporting\` | Reporting | No | Yes | Retrieves app assignment details | | `Get-IntunePolicyAssignments.ps1` | `Reporting\` | Reporting | No | Yes | Retrieves policy assignments | | `Get-IntuneWin32AppDetails.ps1` | `Reporting\` | Reporting | No | Yes | Retrieves Win32 app details | -| `Export-IntuneDeviceReport.ps1` | `Reporting\` | Reporting | No | Yes | Exports comprehensive device reports | +| `Export-IntuneDeviceReport.ps1` | `Reporting\` | Reporting | No | Yes | Exports device reports | | `Get-IntuneDeviceLogs.ps1` | `Troubleshooting\` | Troubleshooting | Yes | No | Collects Intune-related logs | | `Disable-PrintSpoolerService.ps1` | `Security\` | Service Management | Yes | No | Disables Print Spooler service | | `Enable-PrintSpoolerService.ps1` | `Security\` | Service Management | Yes | No | Enables Print Spooler service | | `Disable-SmartCardLogonEnforcement.ps1` | `Security\` | Service Management | Yes | No | Disables smart card logon enforcement | -| `Enable-SmartCardLogonEnforcement.ps1` | `Security\` | Service Management | Yes | No | Enables smart card logon enforcement | +| `Enable-SmartCardLogonEnforcement.ps1` | `Security\` | Service Management | Yes | No | Enables smart card logon enforcement (lockout risk) | | `Test-IntuneConnectivity.ps1` | `Troubleshooting\` | Testing | No | No | Tests connectivity to Intune endpoints | -| `IntuneCommon.psm1` | `Common\` | Module | No | No | Common functions module | +| `IntuneCommon.psd1` / `.psm1` | `Common\` | Module | No | No | Common functions module | --- diff --git a/Remediation/Repair-MultipleIntuneMDMCert.ps1 b/Remediation/Repair-MultipleIntuneMDMCert.ps1 index 164dd49..3655da7 100644 --- a/Remediation/Repair-MultipleIntuneMDMCert.ps1 +++ b/Remediation/Repair-MultipleIntuneMDMCert.ps1 @@ -91,6 +91,13 @@ try } } + # -WhatIf removes nothing, so the store still holds every certificate and the check below + # would report a failure. Nothing changed, so there is nothing to verify. + if ($WhatIfPreference) { + Write-Host "WhatIf: no certificates were removed." + exit 0 + } + # Verify the remediation was successful # Query the certificate store again to confirm only one certificate remains $remainingCertificates = Get-ChildItem -Path $certStorePath -ErrorAction Stop | Where-Object {$_.Issuer -eq "CN=Microsoft Intune MDM Device CA"} diff --git a/Remediation/Set-OfficeUpdateChannel.ps1 b/Remediation/Set-OfficeUpdateChannel.ps1 index 34b46b9..fa77421 100644 --- a/Remediation/Set-OfficeUpdateChannel.ps1 +++ b/Remediation/Set-OfficeUpdateChannel.ps1 @@ -10,6 +10,11 @@ with Detect-OfficeUpdateChannel.ps1. It should be run when Office is not on the Semi-Annual channel or not on the latest version. + If Office Click-to-Run is not installed, the device is not applicable: the script + says so and exits 0. Run the script in 64-bit PowerShell. If it is started in a + 32-bit host on a 64-bit system it relaunches itself in 64-bit PowerShell and + forwards its switches (-WhatIf, -Verbose). + .EXAMPLE .\Set-OfficeUpdateChannel.ps1 @@ -18,9 +23,10 @@ .NOTES Requires: Administrator privileges - Requires: Office Click-to-Run installation + Requires: Office Click-to-Run installation (not applicable otherwise) + Intune Remediations contract: set "Run script in 64-bit PowerShell" to Yes. Exit Codes: - - 0: Remediation successful (Office configured to Semi-Annual channel) + - 0: Remediation successful, already compliant, not applicable (no Click-to-Run), or -WhatIf run - 1: Remediation failed or error occurred #> @@ -28,6 +34,145 @@ # Define script parameters param() +# Build the argument list used to relaunch this script in 64-bit PowerShell. +# Switches that were passed (-WhatIf, -Verbose) are forwarded so the 64-bit child behaves the same. +function Get-RelaunchArgumentList { + [CmdletBinding()] + param( + [Parameter(Mandatory=$true)] + [string]$ScriptPath, + + [Parameter(Mandatory=$false)] + [hashtable]$BoundParameters = @{} + ) + + $arguments = @('-ExecutionPolicy', 'Bypass', '-NoProfile', '-File', $ScriptPath) + foreach ($key in $BoundParameters.Keys) { + $value = $BoundParameters[$key] + if ($value -is [System.Management.Automation.SwitchParameter]) { + if ($value.IsPresent) { $arguments += "-$key" } + } + } + return $arguments +} + +# Reduce the Office release data for one channel to a single CDN base URL and a latest version. +# officeVersions is a list and every entry repeats the CDN URL, so member enumeration returns an array. +# Writing that array to the registry is what broke this script before, so insist on exactly one URL. +function Get-ChannelInfo { + [CmdletBinding()] + param( + [Parameter(Mandatory=$true)] + $CloudVersionInfo, + + [Parameter(Mandatory=$true)] + [string]$ChannelId + ) + + $channel = @($CloudVersionInfo | Where-Object { $_.channelId -eq $ChannelId }) | Select-Object -First 1 + if ($null -eq $channel) { + throw "Could not find $ChannelId channel information from Microsoft." + } + + $cdnUrls = @($channel.officeVersions | ForEach-Object { $_.cdnBaseUrl } | Where-Object { $_ } | Sort-Object -Unique) + if ($cdnUrls.Count -ne 1) { + throw "Expected exactly one CDN base URL for the $ChannelId channel but found $($cdnUrls.Count)." + } + + [PSCustomObject]@{ + ChannelId = $ChannelId + CdnBaseUrl = [string]$cdnUrls[0] + LatestVersion = [string]$channel.latestversion + } +} + +# Read one registry value, or $null if it is missing. +# Get-ItemPropertyValue throws a terminating error for a missing value and -ErrorAction SilentlyContinue does not stop it. +function Get-RegistryValueOrNull { + [CmdletBinding()] + param( + [Parameter(Mandatory=$true)] + [string]$Path, + + [Parameter(Mandatory=$true)] + [string]$Name + ) + + $properties = Get-ItemProperty -Path $Path -ErrorAction SilentlyContinue + if ($null -eq $properties) { return $null } + $property = $properties.PSObject.Properties[$Name] + if ($null -eq $property) { return $null } + return $property.Value +} + +# Find the Click-to-Run updater. OfficeC2RClient.exe lives under Common Files, not under Office16. +function Get-OfficeUpdaterPath { + [CmdletBinding()] + param() + + $roots = @($env:CommonProgramW6432, $env:CommonProgramFiles, ${env:CommonProgramFiles(x86)}) | Where-Object { $_ } | Select-Object -Unique + foreach ($root in $roots) { + $candidate = Join-Path $root 'Microsoft Shared\ClickToRun\OfficeC2RClient.exe' + if (Test-Path -Path $candidate) { return $candidate } + } + return $null +} + +# Function to invoke Office API with retry logic +# Handles transient failures (429, 503, etc.) with exponential backoff +function Invoke-OfficeApiWithRetry { + [CmdletBinding()] + param( + [Parameter(Mandatory=$true)] + [string]$Uri, + + [Parameter(Mandatory=$false)] + [int]$MaxRetries = 3, + + [Parameter(Mandatory=$false)] + [int]$InitialDelaySeconds = 2 + ) + + $retryCount = 0 + $delaySeconds = $InitialDelaySeconds + + while ($retryCount -le $MaxRetries) { + try { + $response = Invoke-RestMethod -Uri $Uri -ErrorAction Stop + return $response + } + catch { + $statusCode = $null + if ($_.Exception.Response) { $statusCode = [int]$_.Exception.Response.StatusCode } + + # Retryable: 429 Too Many Requests, 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout + if ($statusCode -in @(429, 502, 503, 504) -and $retryCount -lt $MaxRetries) { + $retryCount++ + Write-Verbose "Office API call failed with status $statusCode. Retrying in $delaySeconds seconds (attempt $retryCount of $MaxRetries)..." + Start-Sleep -Seconds $delaySeconds + $delaySeconds = $delaySeconds * 2 + } + else { + throw + } + } + } +} + +# Architecture check: if running as a 32-bit process on a 64-bit system, relaunch as 64-bit. +# Intune Remediations run in 32-bit PowerShell unless told otherwise, and a 32-bit host can be +# redirected to WOW6432Node when it reads HKLM\SOFTWARE. +if ($env:PROCESSOR_ARCHITEW6432 -and $env:PROCESSOR_ARCHITEW6432 -ne "ARM64") +{ + $sysNativePowerShell = "$($env:WINDIR)\SysNative\WindowsPowerShell\v1.0\powershell.exe" + if (Test-Path $sysNativePowerShell) + { + $relaunchArguments = Get-RelaunchArgumentList -ScriptPath $PSCommandPath -BoundParameters $PSBoundParameters + & $sysNativePowerShell @relaunchArguments + exit $LASTEXITCODE + } +} + # Main script execution wrapped in try-catch for error handling try { @@ -40,156 +185,95 @@ try } # Check if Office Click-to-Run is installed - # Verify the Office configuration registry path exists + # No Click-to-Run means there is no channel to set, so the device is not applicable $officeConfigPath = "HKLM:\SOFTWARE\Microsoft\Office\ClickToRun\Configuration" if (-not (Test-Path -Path $officeConfigPath)) { - Write-Error "Office Click-to-Run is not installed or configuration path not found." - exit 1 + Write-Host "Office Click-to-Run is not installed. Not applicable, nothing to remediate." + exit 0 } Write-Host "Starting Office update channel remediation..." -ForegroundColor Yellow - # Function to invoke Office API with retry logic - # Handles transient failures (429, 503, etc.) with exponential backoff - function Invoke-OfficeApiWithRetry { - [CmdletBinding()] - param( - [Parameter(Mandatory=$true)] - [string]$Uri, - - [Parameter(Mandatory=$false)] - [int]$MaxRetries = 3, - - [Parameter(Mandatory=$false)] - [int]$InitialDelaySeconds = 2 - ) - - $retryCount = 0 - $delaySeconds = $InitialDelaySeconds - - while ($retryCount -le $MaxRetries) { - try { - $response = Invoke-RestMethod -Uri $Uri -ErrorAction Stop - return $response - } - catch { - $statusCode = $_.Exception.Response.StatusCode.value__ - - # Check if this is a retryable error (429 Too Many Requests, 503 Service Unavailable, 502 Bad Gateway, 504 Gateway Timeout) - if ($statusCode -in @(429, 502, 503, 504) -and $retryCount -lt $MaxRetries) { - $retryCount++ - Write-Verbose "Office API call failed with status $statusCode. Retrying in $delaySeconds seconds (attempt $retryCount of $MaxRetries)..." - Start-Sleep -Seconds $delaySeconds - # Exponential backoff: double the delay for next retry - $delaySeconds = $delaySeconds * 2 - } - else { - # Not a retryable error or max retries reached - throw - } - } - } - } - # Query Microsoft's Office release information service to get the latest available versions - # This provides up-to-date information about all Office update channels and their latest versions Write-Host "Querying Microsoft Office release information..." -ForegroundColor Yellow $CloudVersionInfo = Invoke-OfficeApiWithRetry -Uri 'https://clients.config.office.net/releases/v1.0/OfficeReleases' - - # Find the Semi-Annual channel information - # Filter the cloud version information to find the Semi-Annual channel - $semiAnnualChannel = $CloudVersionInfo | Where-Object { $_.channelId -eq "SemiAnnual" } - - if ($null -eq $semiAnnualChannel) { - Write-Error "Could not find Semi-Annual channel information from Microsoft." - exit 1 - } - # Get the Semi-Annual channel CDN base URL - # This URL is used to configure Office to use the Semi-Annual update channel - $semiAnnualCDN = $semiAnnualChannel.OfficeVersions.cdnBaseURL - $latestVersion = $semiAnnualChannel.latestversion + # Reduce the Semi-Annual channel data to one CDN URL and one latest version + $semiAnnual = Get-ChannelInfo -CloudVersionInfo $CloudVersionInfo -ChannelId 'SemiAnnual' + $semiAnnualCDN = $semiAnnual.CdnBaseUrl + $latestVersion = $semiAnnual.LatestVersion Write-Host "Semi-Annual channel latest version: $latestVersion" -ForegroundColor Cyan Write-Host "Semi-Annual channel CDN: $semiAnnualCDN" -ForegroundColor Cyan # Read the current Office configuration from the registry - # Get the current CDN base URL to see what channel is currently configured - $currentChannel = Get-ItemPropertyValue -Path $officeConfigPath -Name "CDNBaseUrl" -ErrorAction SilentlyContinue - - # Check if Office is already configured for Semi-Annual channel + $currentChannel = Get-RegistryValueOrNull -Path $officeConfigPath -Name "CDNBaseUrl" | Select-Object -Last 1 + if ($currentChannel -eq $semiAnnualCDN) { Write-Host "Office is already configured for Semi-Annual channel." -ForegroundColor Green - - # Check if Office is on the latest version - $currentVersion = Get-ItemPropertyValue -Path $officeConfigPath -Name "VersionToReport" -ErrorAction SilentlyContinue + + $currentVersion = Get-RegistryValueOrNull -Path $officeConfigPath -Name "VersionToReport" if ($currentVersion -eq $latestVersion) { Write-Host "Office is already on the latest version ($latestVersion)." -ForegroundColor Green exit 0 } - else { - Write-Host "Office is on version $currentVersion but latest is $latestVersion. Updating..." -ForegroundColor Yellow - } + Write-Host "Office is on version $currentVersion but latest is $latestVersion. Updating..." -ForegroundColor Yellow } else { Write-Host "Current channel: $currentChannel" -ForegroundColor Yellow - + if ($PSCmdlet.ShouldProcess("Office CDNBaseUrl registry value", "Configure Office to use Semi-Annual channel ($semiAnnualCDN)")) { Write-Host "Configuring Office to use Semi-Annual channel..." -ForegroundColor Yellow - - # Set the CDN base URL to Semi-Annual channel - # This configures Office to use the Semi-Annual update channel - Set-ItemProperty -Path $officeConfigPath -Name "CDNBaseUrl" -Value $semiAnnualCDN -Force -ErrorAction Stop + Set-ItemProperty -Path $officeConfigPath -Name "CDNBaseUrl" -Value $semiAnnualCDN -Type String -Force -ErrorAction Stop Write-Host "Office update channel set to Semi-Annual." -ForegroundColor Green } } # Trigger Office update to get the latest version - # Use Office Click-to-Run update mechanism to update Office if ($PSCmdlet.ShouldProcess("Office installation", "Trigger update to latest version ($latestVersion)")) { Write-Host "Triggering Office update to latest version..." -ForegroundColor Yellow - # Check if OfficeClickToRun.exe exists (Office update executable) - $officeUpdatePath = "${env:ProgramFiles}\Microsoft Office\Office16\OfficeClickToRun.exe" - if (-not (Test-Path -Path $officeUpdatePath)) { - # Try alternative path for 64-bit Office on 32-bit system - $officeUpdatePath = "${env:ProgramFiles(x86)}\Microsoft Office\Office16\OfficeClickToRun.exe" + $officeUpdatePath = Get-OfficeUpdaterPath + if (-not $officeUpdatePath) { + # The channel value is written but nothing will pull the update, so this is a failure + Write-Error "OfficeC2RClient.exe was not found under Common Files\Microsoft Shared\ClickToRun. The update was not triggered." + exit 1 } - if (Test-Path -Path $officeUpdatePath) { - # Run Office update in the background - # /update user: This updates Office for the current user - # /update user displaylevel=false: Runs update silently - Write-Host "Starting Office update process..." -ForegroundColor Yellow - Start-Process -FilePath $officeUpdatePath -ArgumentList "/update", "user", "displaylevel=false" -NoNewWindow -Wait -ErrorAction Stop - Write-Host "Office update process completed." -ForegroundColor Green - } - else { - Write-Warning "OfficeClickToRun.exe not found. Office may update automatically on next check." + Write-Host "Starting Office update process..." -ForegroundColor Yellow + $updateProcess = Start-Process -FilePath $officeUpdatePath -ArgumentList "/update", "user", "displaylevel=false" -NoNewWindow -Wait -PassThru -ErrorAction Stop + if ($null -ne $updateProcess -and $updateProcess.ExitCode -ne 0) { + Write-Error "Office updater exited with code $($updateProcess.ExitCode)." + exit 1 } + Write-Host "Office update process completed." -ForegroundColor Green + } + + # -WhatIf changes nothing, so there is nothing to verify. Report success. + if ($WhatIfPreference) { + Write-Host "WhatIf: no changes were made." + exit 0 } # Verify the remediation was successful - # Wait a moment for registry values to update Start-Sleep -Seconds 5 - - # Check the current configuration - $finalChannel = Get-ItemPropertyValue -Path $officeConfigPath -Name "CDNBaseUrl" -ErrorAction SilentlyContinue - $finalVersion = Get-ItemPropertyValue -Path $officeConfigPath -Name "VersionToReport" -ErrorAction SilentlyContinue + + $finalChannel = Get-RegistryValueOrNull -Path $officeConfigPath -Name "CDNBaseUrl" | Select-Object -Last 1 + $finalVersion = Get-RegistryValueOrNull -Path $officeConfigPath -Name "VersionToReport" if ($finalChannel -eq $semiAnnualCDN) { Write-Host "Office is now configured for Semi-Annual channel." -ForegroundColor Green Write-Host "Current version: $finalVersion" -ForegroundColor Cyan Write-Host "Latest version: $latestVersion" -ForegroundColor Cyan - - # Note: Version may not update immediately, but channel is configured correctly + + # The version may not update immediately, but the channel is configured correctly if ($finalVersion -eq $latestVersion) { Write-Host "Office is on the latest version." -ForegroundColor Green } else { Write-Host "Office update is in progress. Version will update to $latestVersion when complete." -ForegroundColor Yellow } - + exit 0 } else { @@ -200,7 +284,6 @@ try # Error handling block - catches exceptions during registry modifications or API calls catch { - # Capture and display the error message with script name for context $errMsg = $_.Exception.Message Write-Error "Set-OfficeUpdateChannel: Failed to set Office update channel - $errMsg" if ($PSBoundParameters.ContainsKey('Verbose')) { @@ -209,7 +292,5 @@ catch Write-Verbose "Inner Exception: $($_.Exception.InnerException.Message)" } } - # Exit with code 1 to indicate an error occurred exit 1 } - diff --git a/Reporting/Export-IntuneDeviceReport.ps1 b/Reporting/Export-IntuneDeviceReport.ps1 index 8222ce6..8104432 100644 --- a/Reporting/Export-IntuneDeviceReport.ps1 +++ b/Reporting/Export-IntuneDeviceReport.ps1 @@ -4,8 +4,14 @@ .DESCRIPTION This script connects to Microsoft Graph API and collects comprehensive device information - including device details, compliance status, app installations, policy assignments, and - other Intune-related information. The collected data is exported to CSV or JSON format. + including device details, the device's compliance policy states and its configuration + profile states. The collected data is exported to CSV or JSON format. Every query is read + through all result pages. + + If a device's compliance or configuration states cannot be read (for example a missing + permission or a 429 after retries), that device gets a CollectionErrors value instead of + blank columns, the report says it is incomplete and the script exits 1. The report file is + still written so the rest of the data is not lost. .PARAMETER AppId The Application (Client) ID of your Entra ID registered app. Can also be provided via @@ -15,105 +21,83 @@ Your Azure AD Tenant ID. Can also be provided via INTUNE_TENANT_ID environment variable. .PARAMETER ClientSecret - The Client Secret of your Entra ID registered app. Can also be provided via + The Client Secret of your Entra ID registered app, as plain text. A secret on the command line + ends up in shell history and process listings; prefer -ClientSecretSecure or the INTUNE_CLIENT_SECRET environment variable. +.PARAMETER ClientSecretSecure + The Client Secret as a SecureString, for example from Read-Host -AsSecureString or a vault. + .PARAMETER DeviceId Optional. The device ID to generate report for. If not specified, generates report for all devices. .PARAMETER OutputPath - Optional. Path to export report file. If not specified, exports to $env:TEMP\IntuneDeviceReport.csv. + Optional. Path to export report file. If not specified, exports to $env:TEMP\IntuneDeviceReport_.csv (or .json). .PARAMETER Format Optional. Export format: "CSV" or "JSON". Default is "CSV". .EXAMPLE - .\Export-IntuneDeviceReport.ps1 -AppId 'your-app-id' -TenantId 'your-tenant-id' -ClientSecret 'your-secret' + .\Export-IntuneDeviceReport.ps1 -AppId 'your-app-id' -TenantId 'your-tenant-id' -ClientSecretSecure (Read-Host -AsSecureString 'Client secret') .EXAMPLE .\Export-IntuneDeviceReport.ps1 -DeviceId 'device-guid' -Format 'JSON' -OutputPath 'C:\Reports\DeviceReport.json' .NOTES - Requires: Microsoft.Graph PowerShell module - Requires: Entra ID App Registration with DeviceManagementManagedDevices.Read.All, DeviceManagementConfiguration.Read.All, and DeviceManagementApps.Read.All permissions + Requires: Entra ID App Registration with the DeviceManagementManagedDevices.Read.All and + DeviceManagementConfiguration.Read.All APPLICATION permissions (admin consent granted). + No apps endpoint is called, so DeviceManagementApps.Read.All is not needed. + Exit Codes: + - 0: Report complete + - 1: A failure, or at least one device's compliance or configuration states could not be retrieved #> [CmdletBinding()] # Define script parameters for credential input and export options -# These allow credentials and export parameters to be passed as command-line arguments param( [Parameter(Mandatory=$false)] [string]$AppId, - + [Parameter(Mandatory=$false)] [string]$TenantId, - + [Parameter(Mandatory=$false)] [string]$ClientSecret, - + + [Parameter(Mandatory=$false)] + [securestring]$ClientSecretSecure, + [Parameter(Mandatory=$false)] [string]$DeviceId, - + [Parameter(Mandatory=$false)] [string]$OutputPath, - + [Parameter(Mandatory=$false)] [ValidateSet("CSV", "JSON")] [string]$Format = "CSV" ) -# Check if Microsoft.Graph module is installed, and install if missing -# This module is required to interact with Microsoft Graph API -if(-not (Get-Module -Name Microsoft.Graph -ListAvailable)) -{ - try { - # Try to install for current user first (doesn't require admin privileges) - # This is the preferred method as it doesn't require elevation - Install-Module -Name Microsoft.Graph -Repository PSGallery -Scope CurrentUser -Force -AllowClobber -SkipPublisherCheck -ErrorAction Stop - Write-Host "Microsoft.Graph module installed successfully for current user." -ForegroundColor Green - } - catch [Exception] { - # If user-scope installation fails, try system-wide installation - # This requires administrator privileges - Write-Warning "Failed to install module for current user: $($_.Exception.Message)" - Write-Host "Attempting system-wide installation (requires admin privileges)..." -ForegroundColor Yellow - try { - Install-Module -Name Microsoft.Graph -Repository PSGallery -Force -AllowClobber -SkipPublisherCheck -ErrorAction Stop - Write-Host "Microsoft.Graph module installed successfully system-wide." -ForegroundColor Green - } - catch { - # If both installation methods fail, exit with error - Write-Error "Failed to install Microsoft.Graph module: $($_.Exception.Message)" - exit 1 - } - } +# Shared Graph helpers: token request, retry, paging, CSV safety +try { + Import-Module (Join-Path $PSScriptRoot '..\Common\IntuneCommon.psd1') -ErrorAction Stop } - -# Import the Microsoft Graph PowerShell module into the current session -# This makes the Graph API cmdlets available for use -try{ - Import-Module -Name Microsoft.Graph -}catch [Exception] { - # Display error message if import fails - Write-Error "Failed to import Microsoft.Graph module: $($_.Exception.Message)" +catch { + Write-Error "Failed to import the IntuneCommon module: $($_.Exception.Message)" exit 1 } -# Credential handling: Check parameters first, then environment variables -# This provides flexibility in how credentials are provided -$appid = if ($AppId) { $AppId } elseif ($env:INTUNE_APP_ID) { $env:INTUNE_APP_ID } else { '' } -$tenantid = if ($TenantId) { $TenantId } elseif ($env:INTUNE_TENANT_ID) { $env:INTUNE_TENANT_ID } else { '' } -$clientsecret = if ($ClientSecret) { $ClientSecret } elseif ($env:INTUNE_CLIENT_SECRET) { $env:INTUNE_CLIENT_SECRET } else { '' } - -# Validate that credentials are not placeholder values -# This prevents accidental use of placeholder credentials -if ($appid -match '^<.*>$' -or $tenantid -match '^<.*>$' -or $clientsecret -match '^<.*>$') { - Write-Error "Please provide valid credentials via parameters or environment variables (INTUNE_APP_ID, INTUNE_TENANT_ID, INTUNE_CLIENT_SECRET)." +# Credential handling: parameters first, then environment variables. Placeholders are rejected. +try { + $credential = Get-IntuneCredential -AppId $AppId -TenantId $TenantId -ClientSecret $ClientSecret -ClientSecretSecure $ClientSecretSecure +} +catch { + Write-Error $_.Exception.Message exit 1 } # Validate DeviceId format if provided -if ($DeviceId -and -not ($DeviceId -match '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$')) { +if ($DeviceId -and -not (Test-GuidFormat -Guid $DeviceId)) { Write-Error "DeviceId must be a valid GUID format." exit 1 } @@ -127,223 +111,156 @@ if (-not $OutputPath) { } # Create output directory if it doesn't exist -# This ensures the directory exists before exporting the report $exportDirectory = Split-Path -Path $OutputPath -Parent if ($exportDirectory -and -not (Test-Path -Path $exportDirectory)) { New-Item -Path $exportDirectory -ItemType Directory -Force | Out-Null } +# Read one per-device state collection. Returns the display names, or records the failure. +# A failure is never turned into an empty list: it is counted and returned as an error text. +function Get-DeviceStateName { + param( + [Parameter(Mandatory=$true)] [string]$ManagedDeviceId, + [Parameter(Mandatory=$true)] [string]$Collection, + [Parameter(Mandatory=$true)] [string]$Label + ) + + try { + $url = "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices('$ManagedDeviceId')/$Collection" + $states = @(Get-GraphApiAllPages -Uri $url -Headers $script:headers) + return [PSCustomObject]@{ Names = (($states | ForEach-Object { $_.displayName }) -join '; '); Error = $null } + } + catch { + $script:collectionErrorCount++ + Write-Verbose "Could not retrieve $Label for device ${ManagedDeviceId}: $($_.Exception.Message)" + return [PSCustomObject]@{ Names = $null; Error = "$Label`: $($_.Exception.Message)" } + } +} + # Main script execution wrapped in try-catch for error handling try { - # Import shared module for Graph API utilities - Import-Module "$PSScriptRoot\..\Common\IntuneCommon.psm1" -Force -ErrorAction Stop - - # Connect to Microsoft Graph API using app registration credentials - # This authenticates the script to access Intune data via Graph API Write-Host "Connecting to Microsoft Graph API..." -ForegroundColor Yellow - - $body = @{ - grant_type = "client_credentials" - scope = "https://graph.microsoft.com/.default" - client_id = $appid - client_secret = $clientsecret - } - - # Request an access token from Microsoft identity platform - # The token is used to authenticate subsequent Graph API requests - $tokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenantid/oauth2/v2.0/token" -Method Post -Body $body - $accessToken = $tokenResponse.access_token - - # Set up headers for Graph API requests - # The access token is included in the Authorization header - $headers = @{ - "Authorization" = "Bearer $accessToken" - "Content-Type" = "application/json" - } - + $script:headers = Get-IntuneGraphHeaders -AppRegistration $credential Write-Host "Successfully connected to Microsoft Graph API." -ForegroundColor Green - - # Initialize array to store device reports - # This will hold all device information retrieved from Graph API + + $script:collectionErrorCount = 0 $deviceReports = @() - - # Determine which devices to query - # If DeviceId is specified, query only that device - # Otherwise, query all devices + if ($DeviceId) { Write-Host "Generating report for device: $DeviceId" -ForegroundColor Yellow - - # Query device details for specific device - # Get comprehensive device information - $deviceUrl = "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices('$DeviceId')" - $device = Invoke-GraphApiWithRetry -Uri $deviceUrl -Headers $headers -Method Get - + + $device = Invoke-GraphApiWithRetry -Uri "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices('$DeviceId')" -Headers $script:headers -Method Get if ($null -eq $device) { Write-Error "Device not found or API returned null response for device ID: $DeviceId" exit 1 } - $devices = @($device) } else { Write-Host "Generating report for all devices..." -ForegroundColor Yellow - - # Query all managed devices from Intune - $devicesUrl = "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices" - $devices = Invoke-GraphApiWithRetry -Uri $devicesUrl -Headers $headers -Method Get - - # Handle pagination - $allDevices = @() - if ($null -ne $devices -and $null -ne $devices.value) { - $allDevices += $devices.value - } - $pageCount = 1 - while ($null -ne $devices -and $null -ne $devices.'@odata.nextLink') { - $pageCount++ - Write-Progress -Activity "Retrieving devices" -Status "Fetching page $pageCount" -PercentComplete -1 - $devices = Invoke-GraphApiWithRetry -Uri $devices.'@odata.nextLink' -Headers $headers -Method Get - if ($null -ne $devices -and $null -ne $devices.value) { - $allDevices += $devices.value - } - } - Write-Progress -Activity "Retrieving devices" -Completed - - $devices = $allDevices + $devices = @(Get-GraphApiAllPages -Uri "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices" -Headers $script:headers) } - + Write-Host "Found $($devices.Count) device(s). Collecting information..." -ForegroundColor Cyan - - # Process each device and build comprehensive report - # Collect all relevant information for each device + $deviceCount = 0 foreach ($device in $devices) { $deviceCount++ Write-Host "Processing device $deviceCount of $($devices.Count): $($device.deviceName)" -ForegroundColor Cyan - - # Query device-specific compliance policy assignments - # Get compliance policies assigned to this specific device - $deviceCompliancePolicies = @() - try { - $deviceCompliancePoliciesUrl = "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices('$($device.id)')/deviceCompliancePolicyStates" - $deviceCompliancePoliciesResponse = Invoke-GraphApiWithRetry -Uri $deviceCompliancePoliciesUrl -Headers $headers -Method Get -ErrorAction SilentlyContinue - if ($deviceCompliancePoliciesResponse -and $deviceCompliancePoliciesResponse.value) { - $deviceCompliancePolicies = $deviceCompliancePoliciesResponse.value - } - } - catch { - Write-Verbose "Could not retrieve compliance policy states for device $($device.id): $($_.Exception.Message)" - } - - # Query device-specific configuration profile assignments - # Get configuration profiles assigned to this specific device - $deviceConfigProfiles = @() - try { - $deviceConfigProfilesUrl = "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices('$($device.id)')/deviceConfigurationStates" - $deviceConfigProfilesResponse = Invoke-GraphApiWithRetry -Uri $deviceConfigProfilesUrl -Headers $headers -Method Get -ErrorAction SilentlyContinue - if ($deviceConfigProfilesResponse -and $deviceConfigProfilesResponse.value) { - $deviceConfigProfiles = $deviceConfigProfilesResponse.value - } - } - catch { - Write-Verbose "Could not retrieve configuration profile states for device $($device.id): $($_.Exception.Message)" - } - - # Create device report object with all available information - $deviceReport = [PSCustomObject]@{ - DeviceId = $device.id - DeviceName = $device.deviceName - UserPrincipalName = $device.userPrincipalName - UserDisplayName = $device.userDisplayName - EnrollmentDateTime = $device.enrolledDateTime - LastSyncDateTime = $device.lastSyncDateTime - ComplianceState = $device.complianceState - ManagementAgent = $device.managementAgent - OperatingSystem = $device.operatingSystem - OSVersion = $device.osVersion - Manufacturer = $device.manufacturer - Model = $device.model - SerialNumber = $device.serialNumber - TotalStorageSpaceInBytes = $device.totalStorageSpaceInBytes - FreeStorageSpaceInBytes = $device.freeStorageSpaceInBytes - ManagedDeviceName = $device.managedDeviceName - DeviceEnrollmentType = $device.deviceEnrollmentType - IsSupervised = $device.isSupervised - IsEncrypted = $device.isEncrypted - JailBroken = $device.jailBroken - PhoneNumber = $device.phoneNumber - IMEI = $device.imei - EASDeviceId = $device.easDeviceId - ExchangeAccessState = $device.exchangeAccessState + + $compliance = Get-DeviceStateName -ManagedDeviceId $device.id -Collection 'deviceCompliancePolicyStates' -Label 'compliance policy states' + $configuration = Get-DeviceStateName -ManagedDeviceId $device.id -Collection 'deviceConfigurationStates' -Label 'configuration profile states' + $errors = @($compliance.Error, $configuration.Error) | Where-Object { $_ } + + $deviceReports += [PSCustomObject][ordered]@{ + DeviceId = $device.id + DeviceName = $device.deviceName + UserPrincipalName = $device.userPrincipalName + UserDisplayName = $device.userDisplayName + EnrollmentDateTime = $device.enrolledDateTime + LastSyncDateTime = $device.lastSyncDateTime + ComplianceState = $device.complianceState + ManagementAgent = $device.managementAgent + OperatingSystem = $device.operatingSystem + OSVersion = $device.osVersion + Manufacturer = $device.manufacturer + Model = $device.model + SerialNumber = $device.serialNumber + TotalStorageSpaceInBytes = $device.totalStorageSpaceInBytes + FreeStorageSpaceInBytes = $device.freeStorageSpaceInBytes + ManagedDeviceName = $device.managedDeviceName + DeviceEnrollmentType = $device.deviceEnrollmentType + IsSupervised = $device.isSupervised + IsEncrypted = $device.isEncrypted + JailBroken = $device.jailBroken + PhoneNumber = $device.phoneNumber + IMEI = $device.imei + EASDeviceId = $device.easDeviceId + ExchangeAccessState = $device.exchangeAccessState ExchangeAccessStateReason = $device.exchangeAccessStateReason - CompliancePolicies = ($deviceCompliancePolicies | ForEach-Object { $_.displayName }) -join '; ' - ConfigurationProfiles = ($deviceConfigProfiles | ForEach-Object { $_.displayName }) -join '; ' - ReportGeneratedDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss" + CompliancePolicies = $compliance.Names + ConfigurationProfiles = $configuration.Names + CollectionErrors = ($errors -join ' | ') + ReportGeneratedDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss" } - - $deviceReports += $deviceReport } - + # Export report based on specified format - # Export to CSV or JSON format as requested Write-Host "`nExporting report to $Format format..." -ForegroundColor Yellow - + if ($Format -eq "JSON") { - # Export to JSON format - # Convert device reports to JSON and save to file $deviceReports | ConvertTo-Json -Depth 10 | Out-File -FilePath $OutputPath -Encoding UTF8 - Write-Host "Report exported to: $OutputPath" -ForegroundColor Green } else { - # Export to CSV format - # Convert device reports to CSV and save to file - $deviceReports | Export-Csv -Path $OutputPath -NoTypeInformation -Encoding UTF8 - Write-Host "Report exported to: $OutputPath" -ForegroundColor Green + $deviceReports | ConvertTo-SafeCsvRecord | Export-Csv -Path $OutputPath -NoTypeInformation -Encoding UTF8 } - + Write-Host "Report exported to: $OutputPath" -ForegroundColor Green + # Verify the export file was created successfully if (-not (Test-Path -Path $OutputPath)) { Write-Error "Export file was not created successfully at: $OutputPath" exit 1 } - - # Verify the file has content + $fileInfo = Get-Item -Path $OutputPath if ($fileInfo.Length -eq 0) { Write-Warning "Export file was created but appears to be empty." } - + # Display summary Write-Host "`nReport Summary:" -ForegroundColor Cyan Write-Host "===============" -ForegroundColor Cyan Write-Host "Devices included: $($deviceReports.Count)" -ForegroundColor White Write-Host "Output format: $Format" -ForegroundColor White Write-Host "Output path: $OutputPath" -ForegroundColor White - + + if ($script:collectionErrorCount -gt 0) { + Write-Error "The report is incomplete: $($script:collectionErrorCount) state request(s) failed. Affected devices have a CollectionErrors value." + exit 1 + } + Write-Host "`nReport generation completed successfully." -ForegroundColor Green exit 0 } # Error handling block - catches exceptions during Graph API calls or export catch { - # Capture and display the error message with script name for context $errMsg = $_.Exception.Message Write-Error "Export-IntuneDeviceReport: Failed to export device report - $errMsg" - - # Provide additional error context if available + if ($_.Exception.Response) { $statusCode = $_.Exception.Response.StatusCode.value__ Write-Verbose "HTTP Status Code: $statusCode" } - + if ($_.Exception.InnerException) { Write-Verbose "Inner Exception: $($_.Exception.InnerException.Message)" } - + if ($PSBoundParameters.ContainsKey('Verbose')) { Write-Verbose "Stack Trace: $($_.ScriptStackTrace)" } - + exit 1 } - diff --git a/Reporting/Get-IntuneAllAppsAssignmentDetails.ps1 b/Reporting/Get-IntuneAllAppsAssignmentDetails.ps1 index 589ed83..1b8f516 100644 --- a/Reporting/Get-IntuneAllAppsAssignmentDetails.ps1 +++ b/Reporting/Get-IntuneAllAppsAssignmentDetails.ps1 @@ -1,330 +1,259 @@ -<# -.SYNOPSIS - Retrieves all applications published in Microsoft Intune and exports their assignment details. - -.DESCRIPTION - This script retrieves all applications published in Microsoft Intune and exports their - assignment details to a CSV file. It connects to Microsoft Graph API using app registration - credentials and retrieves information about each app including its type, version, assignments, - and target groups. - -.PARAMETER AppId - The Application (Client) ID of your Entra ID registered app. Can also be provided via - INTUNE_APP_ID environment variable. - -.PARAMETER TenantId - Your Azure AD Tenant ID. Can also be provided via INTUNE_TENANT_ID environment variable. - -.PARAMETER ClientSecret - The Client Secret of your Entra ID registered app. Can also be provided via - INTUNE_CLIENT_SECRET environment variable. - -.EXAMPLE - .\Get-IntuneAllAppsAssignmentDetails.ps1 -AppId 'your-app-id' -TenantId 'your-tenant-id' -ClientSecret 'your-secret' - -.NOTES - Requires: Microsoft.Graph PowerShell module - Requires: Entra ID App Registration with appropriate Graph API permissions -#> - -[CmdletBinding()] -# Define script parameters for credential input -# These allow credentials to be passed as command-line arguments -param( - [Parameter(Mandatory=$false)] - [string]$AppId, - - [Parameter(Mandatory=$false)] - [string]$TenantId, - - [Parameter(Mandatory=$false)] - [string]$ClientSecret -) - -# Check if Microsoft.Graph module is installed, and install if missing -# This module is required to interact with Microsoft Graph API -if(-not (Get-Module -Name Microsoft.Graph -ListAvailable)) -{ - try { - # Try to install for current user first (doesn't require admin privileges) - # This is the preferred method as it doesn't require elevation - Install-Module -Name Microsoft.Graph -Repository PSGallery -Scope CurrentUser -Force -AllowClobber -SkipPublisherCheck -ErrorAction Stop - Write-Host "Microsoft.Graph module installed successfully for current user." -ForegroundColor Green - } - catch [Exception] { - # If user-scope installation fails, try system-wide installation - # This requires administrator privileges - Write-Warning "Failed to install module for current user: $($_.Exception.Message)" - Write-Host "Attempting system-wide installation (requires admin privileges)..." -ForegroundColor Yellow - try { - Install-Module -Name Microsoft.Graph -Repository PSGallery -Force -AllowClobber -SkipPublisherCheck -ErrorAction Stop - Write-Host "Microsoft.Graph module installed successfully system-wide." -ForegroundColor Green - } - catch { - # If both installation methods fail, exit with error - Write-Error "Failed to install Microsoft.Graph module: $($_.Exception.Message)" - exit 1 - } - } -} - -# Import the Microsoft Graph PowerShell module into the current session -# This makes the Graph API cmdlets available for use -try{ - Import-Module -Name Microsoft.Graph -}catch [Exception] { - # Display error message if import fails - Write-Error "Failed to import Microsoft.Graph module: $($_.Exception.Message)" - exit 1 -} - -# Define the path where the CSV export file will be saved -# Use $env:TEMP for cross-system compatibility -$ExportCSVpath = Join-Path $env:TEMP "Get-IntuneAllAppsAssignmentDetails.csv" - -# Extract the directory path from the full file path -$exportDirectory = Split-Path -Path $ExportCSVpath -Parent - -# Check if the export directory exists, create it if it doesn't -# This prevents errors when trying to write the CSV file -if (-not (Test-Path -Path $exportDirectory)) { - try { - # Create the directory if it doesn't exist - New-Item -Path $exportDirectory -ItemType Directory -Force | Out-Null - Write-Host "Created export directory: $exportDirectory" -ForegroundColor Green - } - catch { - # Exit if directory creation fails - Write-Error "Failed to create export directory: $($_.Exception.Message)" - exit 1 - } -} - -# Credential handling: Check parameters first, then environment variables, then use placeholders -# This provides flexibility in how credentials are provided -$appid = if ($AppId) { $AppId } elseif ($env:INTUNE_APP_ID) { $env:INTUNE_APP_ID } else { '' } -$tenantid = if ($TenantId) { $TenantId } elseif ($env:INTUNE_TENANT_ID) { $env:INTUNE_TENANT_ID } else { '' } -$secret = if ($ClientSecret) { $ClientSecret } elseif ($env:INTUNE_CLIENT_SECRET) { $env:INTUNE_CLIENT_SECRET } else { '' } - -# Validate that credentials are not placeholder values -# This prevents accidental use of placeholder credentials -if ($appid -match '^<.*>$' -or $tenantid -match '^<.*>$' -or $secret -match '^<.*>$') { - Write-Error "Please provide valid credentials via parameters or environment variables (INTUNE_APP_ID, INTUNE_TENANT_ID, INTUNE_CLIENT_SECRET)." - exit 1 -} - -# Prepare the OAuth2 token request body -# This uses the client credentials flow (app-only authentication) -$body = @{ - Grant_Type = "client_credentials" # OAuth2 grant type for app-only authentication - Scope = "https://graph.microsoft.com/.default" # Request all default permissions - Client_Id = $appid # Application ID - Client_Secret = $secret # Application secret -} - -# Request an access token from Microsoft Identity Platform -# This token will be used to authenticate Graph API requests -$connection = Invoke-RestMethod ` - -Uri https://login.microsoftonline.com/$tenantid/oauth2/v2.0/token ` - -Method POST ` - -Body $body - -# Extract the access token from the response -$token = $connection.access_token - -# Convert the token to a SecureString for use with Connect-MgGraph -# This helps protect the token in memory -$accessToken = ConvertTo-SecureString -String $token -AsPlainText -Force - -# Connect to Microsoft Graph using the access token -# -NoWelcome suppresses the welcome message -Connect-MgGraph -AccessToken $accessToken -NoWelcome - -### Main Section ### - -# Define the Graph API version and resource endpoint -# Using Beta version to access the latest features -$graphApiVersion = "Beta" -$Resource = "deviceAppManagement/mobileApps" # Endpoint for retrieving mobile apps - -# Construct the full URI with query parameters -# $expand parameter includes related entities (Assignments, Category, Version) in the response -$uri = "https://graph.microsoft.com/$graphApiVersion/$($Resource)?`$expand=Assignments,Category,Version" - -# Retrieve all apps from Intune -try{ - # Make the Graph API request to get all mobile apps - # .Value property contains the array of apps - $response = Invoke-MgGraphRequest -Method GET -Uri $uri -OutputType PSObject - - # Handle null or empty response - if ($null -eq $response -or $null -eq $response.Value) { - Write-Warning "No apps found or API returned null response" - $Apps = @() - } - else { - $Apps = $response.Value - } -}catch { - # Error handling for API request failures - $ex = $_.Exception - if ($ex.Response) { - Write-Host "Request to $Uri failed with HTTP Status $([int]$ex.Response.StatusCode) $($ex.Response.StatusDescription)" -ForegroundColor Red - # Read and display error response body - try { - $errorResponse = $ex.Response.GetResponseStream() - $reader = New-Object System.IO.StreamReader($errorResponse) - $reader.BaseStream.Position = 0 - $reader.DiscardBufferedData() - $responseBody = $reader.ReadToEnd() - Write-Host "Response content:`n$responseBody" -ForegroundColor Red - } - catch { - Write-Verbose "Could not read error response body: $($_.Exception.Message)" - } - Write-Error "Get-IntuneAllAppsAssignmentDetails: Request to $Uri failed with HTTP Status $($ex.Response.StatusCode) $($ex.Response.StatusDescription)" - } - else { - Write-Error "Get-IntuneAllAppsAssignmentDetails: Request to $Uri failed - $($ex.Exception.Message)" - } - Write-Host - exit 1 -} - -# Display the total number of apps found -if ($Apps -and $Apps.Count -gt 0) { - Write-Host "Number of Apps found is: $($Apps.Count)" -ForegroundColor Cyan -} -else { - Write-Host "No apps found." -ForegroundColor Yellow - exit 0 -} - -# Create an ArrayList to store the output data -# ArrayList is used for better performance when adding items dynamically -$Output=New-Object System.Collections.ArrayList - -# Process each app retrieved from Intune -$appCount = 0 -foreach ($App in $Apps) -{ - $appCount++ - # Display progress indicator - Write-Progress -Activity "Processing Intune Apps" -Status "Processing app $appCount of $($Apps.Count): $($App.displayName)" -PercentComplete (($appCount / $Apps.Count) * 100) - - # Display the current app name being processed - Write-host "App Name: $($App.displayName)" -ForegroundColor Yellow - - # Convert the OData type identifier to a human-readable app type name - # The @odata.type property contains the full type name from Graph API - $AppType = switch($App.'@odata.type'){ - "#microsoft.graph.androidLobApp" { 'Android LOB' } - "#microsoft.graph.androidStoreApp" { 'Google Play' } - "#microsoft.graph.androidManagedStoreWebApp" { 'Android Managed Store Web App' } - "#microsoft.graph.managedAndroidLobApp" { 'Managed Android LOB' } - "#microsoft.graph.managedAndroidStoreApp" { 'Managed Google Play' } - "#microsoft.graph.androidForWorkApp" { 'Android for Work' } - "#microsoft.graph.iosLobApp" { 'iOS LOB' } - "#microsoft.graph.iosStoreApp" { 'iOS Store' } - "#microsoft.graph.managedIOSLobApp" { 'Managed iOS LOB' } - "#microsoft.graph.managedIOSStoreApp" { 'Managed iOS Store' } - "#microsoft.graph.iosVppApp" { 'iOS VPP' } - "#microsoft.graph.iosVppEBook" { 'iOS VPP Ebook' } - "#microsoft.graph.iosiPadOSWebClip" { 'iOS Weblink' } - "#microsoft.graph.webApp" { 'Web Link' } - "#microsoft.graph.microsoftStoreForBusiness" { 'Microsoft Store' } - "#microsoft.graph.winGetApp" { 'New Microsoft Store' } - "#microsoft.graph.windowsStoreApp" { 'Windows Store App' } - "#microsoft.graph.windowsPhoneXAP" { 'Windows Phone XAP' } - "#microsoft.graph.win32LobApp" { 'Win32' } - "#microsoft.graph.windowsAppX" { 'Windows AppX' } - "#microsoft.graph.windowsMicrosoftEdgeApp" { 'Intune Windows Built-in Edge App' } - "#microsoft.graph.windowsMobileMSI" { 'Windows MSI' } - "#microsoft.graph.windowsUniversalAppX" { 'Windows Universl AppX' } - "#microsoft.graph.windowsUniversalAppXContainedApp" { 'Windows Universal AppX Contained App' } - "#microsoft.graph.windowsWebApp" { 'Windows Web App' } - "#microsoft.graph.officeSuiteApp" { 'Intune Windows Built-in M365 App for Enterprise' } - "#microsoft.graph.macOSDmgApp" { 'MacOS DMG' } - "#microsoft.graph.macOSLobApp" { 'MacOS LOB' } - "#microsoft.graph.macOSMdatpApp" { 'MacOS MDATP' } - "#microsoft.graph.macOSMicrosoftDefenderApp" { 'MacOS Defender' } - "#microsoft.graph.macOSMicrosoftEdgeApp" { 'MacOS Edge' } - "#microsoft.graph.macOSOfficeSuiteApp" { 'Intune MacOS Built-in M365 App for Enterprise' } - "#microsoft.graph.macOSPkgApp" { 'MacOS PKG' } - "#microsoft.graph.macOsVppApp" { 'MacOS VPP' } - default { 'Unknown' } # Fallback for unknown app types - } - - # Display the app type - Write-host "App Type: $AppType" -ForegroundColor Cyan - - # Get the app version (may be null for some app types) - $AppVer = $App.displayVersion - Write-host "App Version: $AppVer" - - # Check if the app has any assignments - # Apps can have zero, one, or multiple assignments - If(($null -eq $App.assignments) -or ($App.assignments -eq "") -or ($App.assignments.count -lt 1)) - { - # App has no assignments - add to output with "Not Assigned" - Write-Host "No assignments for this app" - $GroupName = "Not Assigned" - # Add a row to the output array with assignment information - $Output.Add( (New-Object -TypeName PSObject -Property @{"Name"="$($App.displayName)"; "Platform" = "$AppType"; "Version" = "$AppVer"; "Group" = "$GroupName"; "Assignment" = "$null"} ) ) - } - else - { - # App has one or more assignments - process each assignment - foreach($assignment in $App.assignments) - { - # Display the assignment intent (Available or Required) - write-host "Assignment intent: $($assignment.intent)" - - # Determine the target group name based on assignment target type - If ($($assignment.target.'@odata.type') -like "*allLicensedUsersAssignmentTarget"){ - # App is assigned to all licensed users - Write-Host "Published to All Users" - $GroupName = "All Users" - } elseif($($assignment.target.'@odata.type') -like "*allDevicesAssignmentTarget"){ - # App is assigned to all devices - Write-Host "Published to All Devices" - $GroupName = "All Devices" - } - else - { - # App is assigned to a specific Azure AD group - # Need to look up the group display name using the Group ID - write-host "Group ID: $($assignment.target.GroupID)" - # Query Graph API to get the group's display name - try { - $group = Get-MgGroup -GroupId $assignment.target.GroupID -ErrorAction Stop - if ($null -ne $group -and $null -ne $group.DisplayName) { - $GroupName = $group.DisplayName - } - else { - $GroupName = $assignment.target.GroupID - Write-Warning "Could not retrieve group name for Group ID: $($assignment.target.GroupID)" - } - } - catch { - $GroupName = $assignment.target.GroupID - Write-Verbose "Failed to retrieve group name for Group ID: $($assignment.target.GroupID) - $($_.Exception.Message)" - } - } - - # Display the resolved group name - Write-Host "Group Name: $GroupName" - - # Add a row to the output array with all app and assignment details - $Output.Add( (New-Object -TypeName PSObject -Property @{"Name"="$($App.displayName)"; "Platform" = "$AppType"; "Version" = "$AppVer"; "Group" = "$GroupName"; "Assignment" = "$($assignment.intent)"} ) ) - } - } -} -Write-Progress -Activity "Processing Intune Apps" -Completed - -# Export the collected data to CSV file -# Select-Object filters to only the columns we want in the CSV -$output | Select-Object Name,Platform,Version,Assignment,Group | Export-CSV -Path $ExportCSVpath -Encoding utf8 -NoTypeInformation - -# Disconnect from Microsoft Graph to clean up the session -Disconnect-MgGraph +<# +.SYNOPSIS + Retrieves all applications published in Microsoft Intune and exports their assignment details. + +.DESCRIPTION + This script retrieves all applications published in Microsoft Intune and exports their + assignment details to a CSV file. It connects to Microsoft Graph API using app registration + credentials and retrieves information about each app including its type, version, assignments, + and target groups. It uses plain REST calls and the shared IntuneCommon module; it does not need + the Microsoft.Graph PowerShell SDK. + + Each assignment becomes one row. TargetType says what the assignment targets: + "All Users", "All Devices", "Group", or "Excluded group". An excluded group is a group the app is + NOT deployed to, and is never shown as a targeted group. Apps with no assignments get one row with + Group "Not Assigned". + + The query uses the Graph beta endpoint with $expand=Assignments,Category,Version, as the original + script did, and reads every result page. + +.PARAMETER AppId + The Application (Client) ID of your Entra ID registered app. Can also be provided via + INTUNE_APP_ID environment variable. + +.PARAMETER TenantId + Your Azure AD Tenant ID. Can also be provided via INTUNE_TENANT_ID environment variable. + +.PARAMETER ClientSecret + The Client Secret of your Entra ID registered app, as plain text. A secret on the command line + ends up in shell history and process listings; prefer -ClientSecretSecure or the + INTUNE_CLIENT_SECRET environment variable. + +.PARAMETER ClientSecretSecure + The Client Secret as a SecureString, for example from Read-Host -AsSecureString or a vault. + +.PARAMETER ExportCSVpath + Optional. Where to write the CSV file. Default is $env:TEMP\Get-IntuneAllAppsAssignmentDetails.csv. + +.EXAMPLE + .\Get-IntuneAllAppsAssignmentDetails.ps1 -AppId 'your-app-id' -TenantId 'your-tenant-id' -ClientSecretSecure (Read-Host -AsSecureString 'Client secret') + +.EXAMPLE + .\Get-IntuneAllAppsAssignmentDetails.ps1 -ExportCSVpath 'C:\Reports\AppAssignments.csv' + +.NOTES + Requires: Entra ID App Registration with the DeviceManagementApps.Read.All and Group.Read.All + APPLICATION permissions (admin consent granted). + Exit Codes: + - 0: Export written (or no apps found) + - 1: A failure occurred +#> + +[CmdletBinding()] +# Define script parameters for credential input and the export location +param( + [Parameter(Mandatory=$false)] + [string]$AppId, + + [Parameter(Mandatory=$false)] + [string]$TenantId, + + [Parameter(Mandatory=$false)] + [string]$ClientSecret, + + [Parameter(Mandatory=$false)] + [securestring]$ClientSecretSecure, + + [Parameter(Mandatory=$false)] + [string]$ExportCSVpath = (Join-Path $env:TEMP "Get-IntuneAllAppsAssignmentDetails.csv") +) + +# Shared Graph helpers: token request, retry, paging, CSV safety +try { + Import-Module (Join-Path $PSScriptRoot '..\Common\IntuneCommon.psd1') -ErrorAction Stop +} +catch { + Write-Error "Failed to import the IntuneCommon module: $($_.Exception.Message)" + exit 1 +} + +# Credential handling: parameters first, then environment variables. Placeholders are rejected. +try { + $credential = Get-IntuneCredential -AppId $AppId -TenantId $TenantId -ClientSecret $ClientSecret -ClientSecretSecure $ClientSecretSecure +} +catch { + Write-Error $_.Exception.Message + exit 1 +} + +# Create the export directory if it does not exist +$exportDirectory = Split-Path -Path $ExportCSVpath -Parent +if ($exportDirectory -and -not (Test-Path -Path $exportDirectory)) { + try { + New-Item -Path $exportDirectory -ItemType Directory -Force -ErrorAction Stop | Out-Null + Write-Host "Created export directory: $exportDirectory" -ForegroundColor Green + } + catch { + Write-Error "Failed to create export directory: $($_.Exception.Message)" + exit 1 + } +} + +# Convert the OData type identifier to a human-readable app type name +function Get-AppTypeName { + param([string]$ODataType) + + switch ($ODataType) { + "#microsoft.graph.androidLobApp" { 'Android LOB' } + "#microsoft.graph.androidStoreApp" { 'Google Play' } + "#microsoft.graph.androidManagedStoreWebApp" { 'Android Managed Store Web App' } + "#microsoft.graph.managedAndroidLobApp" { 'Managed Android LOB' } + "#microsoft.graph.managedAndroidStoreApp" { 'Managed Google Play' } + "#microsoft.graph.androidForWorkApp" { 'Android for Work' } + "#microsoft.graph.iosLobApp" { 'iOS LOB' } + "#microsoft.graph.iosStoreApp" { 'iOS Store' } + "#microsoft.graph.managedIOSLobApp" { 'Managed iOS LOB' } + "#microsoft.graph.managedIOSStoreApp" { 'Managed iOS Store' } + "#microsoft.graph.iosVppApp" { 'iOS VPP' } + "#microsoft.graph.iosVppEBook" { 'iOS VPP Ebook' } + "#microsoft.graph.iosiPadOSWebClip" { 'iOS Weblink' } + "#microsoft.graph.webApp" { 'Web Link' } + "#microsoft.graph.microsoftStoreForBusiness" { 'Microsoft Store' } + "#microsoft.graph.winGetApp" { 'New Microsoft Store' } + "#microsoft.graph.windowsStoreApp" { 'Windows Store App' } + "#microsoft.graph.windowsPhoneXAP" { 'Windows Phone XAP' } + "#microsoft.graph.win32LobApp" { 'Win32' } + "#microsoft.graph.windowsAppX" { 'Windows AppX' } + "#microsoft.graph.windowsMicrosoftEdgeApp" { 'Intune Windows Built-in Edge App' } + "#microsoft.graph.windowsMobileMSI" { 'Windows MSI' } + "#microsoft.graph.windowsUniversalAppX" { 'Windows Universal AppX' } + "#microsoft.graph.windowsUniversalAppXContainedApp" { 'Windows Universal AppX Contained App' } + "#microsoft.graph.windowsWebApp" { 'Windows Web App' } + "#microsoft.graph.officeSuiteApp" { 'Intune Windows Built-in M365 App for Enterprise' } + "#microsoft.graph.macOSDmgApp" { 'MacOS DMG' } + "#microsoft.graph.macOSLobApp" { 'MacOS LOB' } + "#microsoft.graph.macOSMdatpApp" { 'MacOS MDATP' } + "#microsoft.graph.macOSMicrosoftDefenderApp" { 'MacOS Defender' } + "#microsoft.graph.macOSMicrosoftEdgeApp" { 'MacOS Edge' } + "#microsoft.graph.macOSOfficeSuiteApp" { 'Intune MacOS Built-in M365 App for Enterprise' } + "#microsoft.graph.macOSPkgApp" { 'MacOS PKG' } + "#microsoft.graph.macOsVppApp" { 'MacOS VPP' } + default { 'Unknown' } + } +} + +# Map an assignment target type to the label shown in the TargetType column. +# exclusionGroupAssignmentTarget is a group the app is NOT deployed to. +function Get-TargetTypeName { + param([string]$ODataType) + + if ($ODataType -like "*allLicensedUsersAssignmentTarget") { return 'All Users' } + if ($ODataType -like "*allDevicesAssignmentTarget") { return 'All Devices' } + if ($ODataType -like "*exclusionGroupAssignmentTarget") { return 'Excluded group' } + if ($ODataType -like "*groupAssignmentTarget") { return 'Group' } + return "$ODataType" +} + +# Resolve a group ID to its display name. Cached so each group is looked up once. +$script:groupNameCache = @{} +function Resolve-GroupName { + param([string]$GroupId) + + if ($script:groupNameCache.ContainsKey($GroupId)) { return $script:groupNameCache[$GroupId] } + + $name = $GroupId + try { + $group = Invoke-GraphApiWithRetry -Uri "https://graph.microsoft.com/v1.0/groups/$GroupId" -Headers $script:headers -Method Get + if ($null -ne $group -and $null -ne $group.displayName) { $name = $group.displayName } + else { Write-Warning "Could not retrieve group name for Group ID: $GroupId" } + } + catch { + Write-Verbose "Failed to retrieve group name for Group ID: $GroupId - $($_.Exception.Message)" + } + $script:groupNameCache[$GroupId] = $name + return $name +} + +# Build the output rows for one app: one per assignment, or one "Not Assigned" row +function Get-AppRow { + param([Parameter(Mandatory=$true)] $App) + + $appType = Get-AppTypeName -ODataType $App.'@odata.type' + $appVer = $App.displayVersion + $name = "$($App.displayName)" + $assignments = @($App.assignments) + + if ($assignments.Count -eq 0) { + Write-Host "No assignments for this app" + [PSCustomObject][ordered]@{ Name = $name; Platform = $appType; Version = "$appVer"; Assignment = ""; Group = "Not Assigned"; TargetType = "None" } + return + } + + foreach ($assignment in $assignments) { + Write-Host "Assignment intent: $($assignment.intent)" + $targetType = Get-TargetTypeName -ODataType $assignment.target.'@odata.type' + + if ($targetType -in @('All Users', 'All Devices')) { + $groupName = $targetType + } + elseif ($assignment.target.groupId) { + $groupName = Resolve-GroupName -GroupId $assignment.target.groupId + } + else { + $groupName = $targetType + } + Write-Host "Target: $targetType, Group Name: $groupName" + + [PSCustomObject][ordered]@{ Name = $name; Platform = $appType; Version = "$appVer"; Assignment = "$($assignment.intent)"; Group = $groupName; TargetType = $targetType } + } +} + +try { + Write-Host "Connecting to Microsoft Graph API..." -ForegroundColor Yellow + $script:headers = Get-IntuneGraphHeaders -AppRegistration $credential + + # Beta is used for the Assignments/Category/Version expand, as before. Every page is read: $expand + # makes Graph return small pages, so a single request silently truncated the report on a large tenant. + $uri = "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps?`$expand=Assignments,Category,Version" + $Apps = @(Get-GraphApiAllPages -Uri $uri -Headers $script:headers) +} +catch { + $ex = $_.Exception + if ($ex.Response) { + Write-Error "Get-IntuneAllAppsAssignmentDetails: Request failed with HTTP Status $($ex.Response.StatusCode.value__) - $($ex.Message)" + } + else { + Write-Error "Get-IntuneAllAppsAssignmentDetails: Request failed - $($ex.Message)" + } + exit 1 +} + +if ($Apps.Count -gt 0) { + Write-Host "Number of Apps found is: $($Apps.Count)" -ForegroundColor Cyan +} +else { + Write-Host "No apps found." -ForegroundColor Yellow + exit 0 +} + +$Output = New-Object System.Collections.ArrayList +$appCount = 0 +foreach ($App in $Apps) { + $appCount++ + Write-Progress -Activity "Processing Intune Apps" -Status "Processing app $appCount of $($Apps.Count): $($App.displayName)" -PercentComplete (($appCount / $Apps.Count) * 100) + Write-Host "App Name: $($App.displayName)" -ForegroundColor Yellow + + foreach ($row in @(Get-AppRow -App $App)) { [void]$Output.Add($row) } +} +Write-Progress -Activity "Processing Intune Apps" -Completed + +# Export the collected data to CSV file, formula-safe +try { + $Output | ConvertTo-SafeCsvRecord | Export-Csv -Path $ExportCSVpath -Encoding UTF8 -NoTypeInformation -ErrorAction Stop + Write-Host "Exported $($Output.Count) row(s) to: $ExportCSVpath" -ForegroundColor Green +} +catch { + Write-Error "Get-IntuneAllAppsAssignmentDetails: Failed to write $ExportCSVpath - $($_.Exception.Message)" + exit 1 +} +exit 0 diff --git a/Reporting/Get-IntuneDeviceCompliance.ps1 b/Reporting/Get-IntuneDeviceCompliance.ps1 index 2d1ce1e..a9291b3 100644 --- a/Reporting/Get-IntuneDeviceCompliance.ps1 +++ b/Reporting/Get-IntuneDeviceCompliance.ps1 @@ -5,8 +5,20 @@ .DESCRIPTION This script connects to Microsoft Graph API and retrieves compliance status information for Intune-managed devices. It can query compliance for a specific device, all devices, - or devices for a specific user. The script displays compliance policy assignments, - compliance state, and any non-compliance reasons. + or devices for a specific user. + + For each device it reads the device's own compliance policy states + (managedDevices/{id}/deviceCompliancePolicyStates). CompliancePolicies lists every policy that + applies to that device with its state, for example "Baseline (compliant); BitLocker (nonCompliant)", + and NonCompliantPolicies lists the ones in the nonCompliant, error or conflict state. Per-setting + non-compliance reasons are not retrieved. + + That is one extra request per device. Use -SkipPolicyStates on a large tenant to skip it; the + policy columns are then blank. + + If a device's policy states cannot be read (for example a missing permission or a 429 after + retries) the device gets a CollectionError value, the report says it is incomplete and the + script exits 1. A blank policy column is never used to mean "failed". .PARAMETER AppId The Application (Client) ID of your Entra ID registered app. Can also be provided via @@ -16,9 +28,13 @@ Your Azure AD Tenant ID. Can also be provided via INTUNE_TENANT_ID environment variable. .PARAMETER ClientSecret - The Client Secret of your Entra ID registered app. Can also be provided via + The Client Secret of your Entra ID registered app, as plain text. A secret on the command line + ends up in shell history and process listings; prefer -ClientSecretSecure or the INTUNE_CLIENT_SECRET environment variable. +.PARAMETER ClientSecretSecure + The Client Secret as a SecureString, for example from Read-Host -AsSecureString or a vault. + .PARAMETER DeviceId Optional. The device ID to query compliance for. If not specified, retrieves all devices. @@ -29,130 +45,98 @@ .PARAMETER ExportPath Optional. Path to export results to CSV file. If not specified, results are displayed only. +.PARAMETER SkipPolicyStates + Optional switch. Do not read each device's policy states (saves one request per device). + .EXAMPLE - .\Get-IntuneDeviceCompliance.ps1 -AppId 'your-app-id' -TenantId 'your-tenant-id' -ClientSecret 'your-secret' + .\Get-IntuneDeviceCompliance.ps1 -AppId 'your-app-id' -TenantId 'your-tenant-id' -ClientSecretSecure (Read-Host -AsSecureString 'Client secret') .EXAMPLE - .\Get-IntuneDeviceCompliance.ps1 -DeviceId 'device-guid' -AppId 'your-app-id' -TenantId 'your-tenant-id' -ClientSecret 'your-secret' + .\Get-IntuneDeviceCompliance.ps1 -DeviceId 'device-guid' -ExportPath 'C:\Temp\ComplianceReport.csv' .EXAMPLE .\Get-IntuneDeviceCompliance.ps1 -UserPrincipalName 'user@domain.com' -ExportPath 'C:\Temp\ComplianceReport.csv' .NOTES - Requires: Microsoft.Graph PowerShell module - Requires: Entra ID App Registration with DeviceManagementManagedDevices.Read.All and DeviceManagementConfiguration.Read.All permissions + Requires: Entra ID App Registration with the DeviceManagementManagedDevices.Read.All and + DeviceManagementConfiguration.Read.All APPLICATION permissions (admin consent granted). + Exit Codes: + - 0: Report complete + - 1: A failure, or at least one device's policy states could not be retrieved #> [CmdletBinding()] # Define script parameters for credential input and query options -# These allow credentials and query parameters to be passed as command-line arguments param( [Parameter(Mandatory=$false)] [string]$AppId, - + [Parameter(Mandatory=$false)] [string]$TenantId, - + [Parameter(Mandatory=$false)] [string]$ClientSecret, - + + [Parameter(Mandatory=$false)] + [securestring]$ClientSecretSecure, + [Parameter(Mandatory=$false)] [string]$DeviceId, - + [Parameter(Mandatory=$false)] [string]$UserPrincipalName, - + [Parameter(Mandatory=$false)] [string]$ExportPath, - + + [Parameter(Mandatory=$false)] + [switch]$SkipPolicyStates, + [Parameter(Mandatory=$false)] [ValidateRange(1, 10)] [int]$MaxRetries = 3, - + [Parameter(Mandatory=$false)] [ValidateRange(1, 60)] [int]$InitialDelaySeconds = 2 ) -# Check if Microsoft.Graph module is installed, and install if missing -# This module is required to interact with Microsoft Graph API -if(-not (Get-Module -Name Microsoft.Graph -ListAvailable)) -{ - try { - # Try to install for current user first (doesn't require admin privileges) - # This is the preferred method as it doesn't require elevation - Install-Module -Name Microsoft.Graph -Repository PSGallery -Scope CurrentUser -Force -AllowClobber -SkipPublisherCheck -ErrorAction Stop - Write-Host "Microsoft.Graph module installed successfully for current user." -ForegroundColor Green - } - catch [Exception] { - # If user-scope installation fails, try system-wide installation - # This requires administrator privileges - Write-Warning "Failed to install module for current user: $($_.Exception.Message)" - Write-Host "Attempting system-wide installation (requires admin privileges)..." -ForegroundColor Yellow - try { - Install-Module -Name Microsoft.Graph -Repository PSGallery -Force -AllowClobber -SkipPublisherCheck -ErrorAction Stop - Write-Host "Microsoft.Graph module installed successfully system-wide." -ForegroundColor Green - } - catch { - # If both installation methods fail, exit with error - Write-Error "Failed to install Microsoft.Graph module: $($_.Exception.Message)" - exit 1 - } - } +# Shared Graph helpers: token request, retry, paging, OData escaping, CSV safety +try { + Import-Module (Join-Path $PSScriptRoot '..\Common\IntuneCommon.psd1') -ErrorAction Stop } - -# Import the Microsoft Graph PowerShell module into the current session -# This makes the Graph API cmdlets available for use -try{ - Import-Module -Name Microsoft.Graph -}catch [Exception] { - # Display error message if import fails - Write-Error "Failed to import Microsoft.Graph module: $($_.Exception.Message)" +catch { + Write-Error "Failed to import the IntuneCommon module: $($_.Exception.Message)" exit 1 } -# Credential handling: Check parameters first, then environment variables -# This provides flexibility in how credentials are provided -$appid = if ($AppId) { $AppId } elseif ($env:INTUNE_APP_ID) { $env:INTUNE_APP_ID } else { '' } -$tenantid = if ($TenantId) { $TenantId } elseif ($env:INTUNE_TENANT_ID) { $env:INTUNE_TENANT_ID } else { '' } -$clientsecret = if ($ClientSecret) { $ClientSecret } elseif ($env:INTUNE_CLIENT_SECRET) { $env:INTUNE_CLIENT_SECRET } else { '' } - -# Validate that credentials are not placeholder values -# This prevents accidental use of placeholder credentials -if ($appid -match '^<.*>$' -or $tenantid -match '^<.*>$' -or $clientsecret -match '^<.*>$') { - Write-Error "Please provide valid credentials via parameters or environment variables (INTUNE_APP_ID, INTUNE_TENANT_ID, INTUNE_CLIENT_SECRET)." +# Credential handling: parameters first, then environment variables. Placeholders are rejected. +try { + $credential = Get-IntuneCredential -AppId $AppId -TenantId $TenantId -ClientSecret $ClientSecret -ClientSecretSecure $ClientSecretSecure +} +catch { + Write-Error $_.Exception.Message exit 1 } # Validate DeviceId format if provided -if ($DeviceId -and -not ($DeviceId -match '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$')) { +if ($DeviceId -and -not (Test-GuidFormat -Guid $DeviceId)) { Write-Error "DeviceId must be a valid GUID format." exit 1 } # Validate UserPrincipalName format if provided -if ($UserPrincipalName -and -not ($UserPrincipalName -match '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$')) { +if ($UserPrincipalName -and -not (Test-EmailFormat -Email $UserPrincipalName)) { Write-Error "UserPrincipalName must be a valid email address format." exit 1 } -# Sanitize UserPrincipalName input for OData query -if ($UserPrincipalName) { - # Remove potentially dangerous characters from OData filter - $UserPrincipalName = $UserPrincipalName -replace "[';]", "" - if ([string]::IsNullOrWhiteSpace($UserPrincipalName)) { - Write-Error "UserPrincipalName cannot be empty after sanitization." - exit 1 - } -} - # Validate ExportPath if provided if ($ExportPath) { - # Check if the directory exists or can be created $exportDirectory = Split-Path -Path $ExportPath -Parent if ($exportDirectory -and -not (Test-Path -Path $exportDirectory)) { try { - New-Item -Path $exportDirectory -ItemType Directory -Force | Out-Null + New-Item -Path $exportDirectory -ItemType Directory -Force -ErrorAction Stop | Out-Null Write-Verbose "Created export directory: $exportDirectory" } catch { @@ -160,8 +144,8 @@ if ($ExportPath) { exit 1 } } - - # Check if file path is writable (if file exists) or directory is writable + + # Check the file is writable if it already exists if (Test-Path -Path $ExportPath) { try { $testFile = [System.IO.File]::OpenWrite($ExportPath) @@ -174,213 +158,112 @@ if ($ExportPath) { } } +# Build one report row for a device, reading the device's own compliance policy states. +# Errors are recorded on the row and counted; they are never turned into an empty policy list. +function Get-ComplianceRow { + param([Parameter(Mandatory=$true)] $Device) + + $policyText = $null + $nonCompliantText = $null + $collectionError = $null + + if (-not $SkipPolicyStates) { + try { + $url = "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices('$($Device.id)')/deviceCompliancePolicyStates" + $states = @(Get-GraphApiAllPages -Uri $url -Headers $script:headers -MaxRetries $MaxRetries -InitialDelaySeconds $InitialDelaySeconds) + $policyText = ($states | ForEach-Object { "$($_.displayName) ($($_.state))" }) -join '; ' + $nonCompliantText = ($states | Where-Object { $_.state -in @('nonCompliant', 'error', 'conflict') } | ForEach-Object { $_.displayName }) -join '; ' + } + catch { + $collectionError = "Could not read policy states: $($_.Exception.Message)" + $script:collectionErrorCount++ + Write-Verbose "$collectionError (device $($Device.id))" + } + } + + [PSCustomObject][ordered]@{ + DeviceId = $Device.id + DeviceName = $Device.deviceName + UserPrincipalName = $Device.userPrincipalName + ComplianceState = $Device.complianceState + LastSyncDateTime = $Device.lastSyncDateTime + OSVersion = $Device.osVersion + ManagementAgent = $Device.managementAgent + CompliancePolicies = $policyText + NonCompliantPolicies = $nonCompliantText + CollectionError = $collectionError + } +} + # Main script execution wrapped in try-catch for error handling try { - # Import shared module for Graph API utilities - Import-Module "$PSScriptRoot\..\Common\IntuneCommon.psm1" -Force -ErrorAction Stop - - # Connect to Microsoft Graph API using app registration credentials - # This authenticates the script to access Intune data via Graph API Write-Host "Connecting to Microsoft Graph API..." -ForegroundColor Yellow - - $body = @{ - grant_type = "client_credentials" - scope = "https://graph.microsoft.com/.default" - client_id = $appid - client_secret = $clientsecret - } - - # Request an access token from Microsoft identity platform - # The token is used to authenticate subsequent Graph API requests - $tokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenantid/oauth2/v2.0/token" -Method Post -Body $body - $accessToken = $tokenResponse.access_token - - # Set up headers for Graph API requests - # The access token is included in the Authorization header - $headers = @{ - "Authorization" = "Bearer $accessToken" - "Content-Type" = "application/json" - } - + $script:headers = Get-IntuneGraphHeaders -AppRegistration $credential Write-Host "Successfully connected to Microsoft Graph API." -ForegroundColor Green - - # Initialize array to store compliance results - # This will hold all compliance information retrieved from Graph API + + $script:collectionErrorCount = 0 $complianceResults = @() - - # Determine which devices to query based on provided parameters - # If DeviceId is specified, query only that device - # If UserPrincipalName is specified, query all devices for that user - # Otherwise, query all devices + if ($DeviceId) { Write-Host "Querying compliance for device: $DeviceId" -ForegroundColor Yellow - - # Query device compliance status for specific device - # The Graph API endpoint returns compliance state and policy assignments - $deviceComplianceUrl = "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices('$DeviceId')?`$expand=detectedApps" - $device = Invoke-GraphApiWithRetry -Uri $deviceComplianceUrl -Headers $headers -Method Get - + + $device = Invoke-GraphApiWithRetry -Uri "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices('$DeviceId')" -Headers $script:headers -Method Get -MaxRetries $MaxRetries -InitialDelaySeconds $InitialDelaySeconds if ($null -eq $device) { Write-Error "Device not found or API returned null response for device ID: $DeviceId" exit 1 } - - # Query compliance policies for this device - # Get all compliance policies that apply to this device - $compliancePoliciesUrl = "https://graph.microsoft.com/v1.0/deviceManagement/deviceCompliancePolicies" - $compliancePolicies = Invoke-GraphApiWithRetry -Uri $compliancePoliciesUrl -Headers $headers -Method Get - - # Handle null or empty response - $compliancePolicyNames = @() - if ($null -ne $compliancePolicies -and $null -ne $compliancePolicies.value) { - $compliancePolicyNames = $compliancePolicies.value | ForEach-Object { $_.displayName } - } - - # Create compliance result object - $complianceResult = [PSCustomObject]@{ - DeviceId = $device.id - DeviceName = $device.deviceName - UserPrincipalName = $device.userPrincipalName - ComplianceState = $device.complianceState - LastSyncDateTime = $device.lastSyncDateTime - OSVersion = $device.osVersion - ManagementAgent = $device.managementAgent - CompliancePolicies = ($compliancePolicyNames) -join '; ' - } - - $complianceResults += $complianceResult + $devices = @($device) } elseif ($UserPrincipalName) { Write-Host "Querying compliance for devices owned by: $UserPrincipalName" -ForegroundColor Yellow - - # Query all devices for the specified user - # Filter devices by user principal name - $devicesUrl = "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices?`$filter=userPrincipalName eq '$UserPrincipalName'" - $devices = Invoke-GraphApiWithRetry -Uri $devicesUrl -Headers $headers -Method Get - - # Handle null or empty response - if ($null -eq $devices -or $null -eq $devices.value) { - Write-Warning "No devices found for user: $UserPrincipalName" - $devices = @{ value = @() } - } - - # Query compliance policies - $compliancePoliciesUrl = "https://graph.microsoft.com/v1.0/deviceManagement/deviceCompliancePolicies" - $compliancePolicies = Invoke-GraphApiWithRetry -Uri $compliancePoliciesUrl -Headers $headers -Method Get - - # Handle null or empty response - $compliancePolicyNames = @() - if ($null -ne $compliancePolicies -and $null -ne $compliancePolicies.value) { - $compliancePolicyNames = $compliancePolicies.value | ForEach-Object { $_.displayName } - } - - foreach ($device in $devices.value) { - $complianceResult = [PSCustomObject]@{ - DeviceId = $device.id - DeviceName = $device.deviceName - UserPrincipalName = $device.userPrincipalName - ComplianceState = $device.complianceState - LastSyncDateTime = $device.lastSyncDateTime - OSVersion = $device.osVersion - ManagementAgent = $device.managementAgent - CompliancePolicies = ($compliancePolicyNames) -join '; ' - } - - $complianceResults += $complianceResult - } + + # The quote is doubled (OData's escape) and the whole filter is URL-encoded, so a + in the UPN survives + $filter = "userPrincipalName eq $(ConvertTo-ODataStringLiteral -Value $UserPrincipalName)" + $devicesUrl = "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices?`$filter=$([uri]::EscapeDataString($filter))" + $devices = @(Get-GraphApiAllPages -Uri $devicesUrl -Headers $script:headers -MaxRetries $MaxRetries -InitialDelaySeconds $InitialDelaySeconds) + if ($devices.Count -eq 0) { Write-Warning "No devices found for user: $UserPrincipalName" } } else { Write-Host "Querying compliance for all devices..." -ForegroundColor Yellow - - # Query all managed devices from Intune - $devicesUrl = "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices" - $devices = Invoke-GraphApiWithRetry -Uri $devicesUrl -Headers $headers -Method Get - - # Handle null or empty response and pagination - $allDevices = @() - if ($null -ne $devices -and $null -ne $devices.value) { - $allDevices += $devices.value - } - - # Query compliance policies - $compliancePoliciesUrl = "https://graph.microsoft.com/v1.0/deviceManagement/deviceCompliancePolicies" - $compliancePolicies = Invoke-GraphApiWithRetry -Uri $compliancePoliciesUrl -Headers $headers -Method Get - - # Extract policy names from response - $compliancePolicyNames = @() - if ($null -ne $compliancePolicies -and $null -ne $compliancePolicies.value) { - $compliancePolicyNames = $compliancePolicies.value | ForEach-Object { $_.displayName } - } - - # Handle pagination for devices - $pageCount = 1 - while ($null -ne $devices -and $null -ne $devices.'@odata.nextLink') { - $pageCount++ - Write-Progress -Activity "Retrieving devices" -Status "Fetching page $pageCount" -PercentComplete -1 - $devices = Invoke-GraphApiWithRetry -Uri $devices.'@odata.nextLink' -Headers $headers -Method Get - if ($null -ne $devices -and $null -ne $devices.value) { - $allDevices += $devices.value - } - } - Write-Progress -Activity "Retrieving devices" -Completed - - foreach ($device in $allDevices) { - $complianceResult = [PSCustomObject]@{ - DeviceId = $device.id - DeviceName = $device.deviceName - UserPrincipalName = $device.userPrincipalName - ComplianceState = $device.complianceState - LastSyncDateTime = $device.lastSyncDateTime - OSVersion = $device.osVersion - ManagementAgent = $device.managementAgent - CompliancePolicies = ($compliancePolicyNames) -join '; ' - } - - $complianceResults += $complianceResult - } + $devices = @(Get-GraphApiAllPages -Uri "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices" -Headers $script:headers -MaxRetries $MaxRetries -InitialDelaySeconds $InitialDelaySeconds) + } + + $deviceCount = 0 + foreach ($device in $devices) { + $deviceCount++ + Write-Progress -Activity "Reading compliance policy states" -Status "Device $deviceCount of $($devices.Count): $($device.deviceName)" -PercentComplete (($deviceCount / $devices.Count) * 100) + $complianceResults += Get-ComplianceRow -Device $device } - + Write-Progress -Activity "Reading compliance policy states" -Completed + # Display results Write-Host "`nCompliance Results:" -ForegroundColor Cyan Write-Host "===================" -ForegroundColor Cyan - + if ($complianceResults.Count -eq 0) { Write-Host "No devices found matching the specified criteria." -ForegroundColor Yellow } else { - # Display each compliance result foreach ($result in $complianceResults) { Write-Host "`nDevice: $($result.DeviceName)" -ForegroundColor Green Write-Host " Device ID: $($result.DeviceId)" -ForegroundColor White Write-Host " User: $($result.UserPrincipalName)" -ForegroundColor White - Write-Host " Compliance State: $($result.ComplianceState)" -ForegroundColor $(if ($result.ComplianceState -eq 'Compliant') { 'Green' } else { 'Red' }) + Write-Host " Compliance State: $($result.ComplianceState)" -ForegroundColor $(if ($result.ComplianceState -eq 'compliant') { 'Green' } else { 'Red' }) Write-Host " Last Sync: $($result.LastSyncDateTime)" -ForegroundColor White Write-Host " OS Version: $($result.OSVersion)" -ForegroundColor White Write-Host " Management Agent: $($result.ManagementAgent)" -ForegroundColor White + if ($result.CompliancePolicies) { Write-Host " Policies: $($result.CompliancePolicies)" -ForegroundColor White } + if ($result.NonCompliantPolicies) { Write-Host " Not compliant with: $($result.NonCompliantPolicies)" -ForegroundColor Red } + if ($result.CollectionError) { Write-Host " ERROR: $($result.CollectionError)" -ForegroundColor Red } } - + # Export to CSV if path is specified if ($ExportPath) { - # Validate export path (should have been validated earlier, but double-check) - $exportDirectory = Split-Path -Path $ExportPath -Parent - if ($exportDirectory -and -not (Test-Path -Path $exportDirectory)) { - try { - New-Item -Path $exportDirectory -ItemType Directory -Force | Out-Null - Write-Verbose "Created export directory: $exportDirectory" - } - catch { - Write-Error "Cannot create export directory: $exportDirectory. Error: $($_.Exception.Message)" - exit 1 - } - } - - # Export results to CSV file try { - $complianceResults | Export-Csv -Path $ExportPath -NoTypeInformation -Encoding UTF8 + $complianceResults | ConvertTo-SafeCsvRecord | Export-Csv -Path $ExportPath -NoTypeInformation -Encoding UTF8 Write-Host "`nResults exported to: $ExportPath" -ForegroundColor Green - - # Verify the export file was created successfully + if (-not (Test-Path -Path $ExportPath)) { Write-Error "Export file was not created successfully at: $ExportPath" exit 1 @@ -392,30 +275,32 @@ try } } } - + + if ($script:collectionErrorCount -gt 0) { + Write-Error "The report is incomplete: policy states could not be read for $($script:collectionErrorCount) device(s). They have a CollectionError value." + exit 1 + } + Write-Host "`nQuery completed successfully." -ForegroundColor Green } # Error handling block - catches exceptions during Graph API calls catch { - # Capture and display the error message with script name for context $errMsg = $_.Exception.Message Write-Error "Get-IntuneDeviceCompliance: Failed to retrieve device compliance information - $errMsg" - - # Provide additional error context if available + if ($_.Exception.Response) { $statusCode = $_.Exception.Response.StatusCode.value__ Write-Verbose "HTTP Status Code: $statusCode" } - + if ($_.Exception.InnerException) { Write-Verbose "Inner Exception: $($_.Exception.InnerException.Message)" } - + if ($PSBoundParameters.ContainsKey('Verbose')) { Write-Verbose "Stack Trace: $($_.ScriptStackTrace)" } - + exit 1 } - diff --git a/Reporting/Get-IntuneDeviceDetails.ps1 b/Reporting/Get-IntuneDeviceDetails.ps1 index 8eaff42..3d004d1 100644 --- a/Reporting/Get-IntuneDeviceDetails.ps1 +++ b/Reporting/Get-IntuneDeviceDetails.ps1 @@ -6,7 +6,8 @@ This script connects to Microsoft Graph API and retrieves comprehensive information about Intune-managed devices including enrollment details, last sync time, management state, hardware information, and device configuration. It can query a specific device - by ID or retrieve all devices. + by ID, search devices by name, or retrieve all devices. Every query is read through all + result pages. .PARAMETER AppId The Application (Client) ID of your Entra ID registered app. Can also be provided via @@ -16,126 +17,105 @@ Your Azure AD Tenant ID. Can also be provided via INTUNE_TENANT_ID environment variable. .PARAMETER ClientSecret - The Client Secret of your Entra ID registered app. Can also be provided via + The Client Secret of your Entra ID registered app, as plain text. A secret on the command line + ends up in shell history and process listings; prefer -ClientSecretSecure or the INTUNE_CLIENT_SECRET environment variable. +.PARAMETER ClientSecretSecure + The Client Secret as a SecureString, for example from Read-Host -AsSecureString or a vault. + .PARAMETER DeviceId Optional. The device ID to query. If not specified, retrieves all devices. .PARAMETER DeviceName - Optional. The device name to search for. Partial matches are supported. + Optional. The device name to search for. This is a substring match (Graph contains()), so + 'LAPTOP-01' finds every device whose name includes it. Wildcard characters (* and %) are + removed, not expanded. .PARAMETER ExportPath Optional. Path to export results to CSV file. If not specified, results are displayed only. .EXAMPLE - .\Get-IntuneDeviceDetails.ps1 -AppId 'your-app-id' -TenantId 'your-tenant-id' -ClientSecret 'your-secret' + .\Get-IntuneDeviceDetails.ps1 -AppId 'your-app-id' -TenantId 'your-tenant-id' -ClientSecretSecure (Read-Host -AsSecureString 'Client secret') .EXAMPLE - .\Get-IntuneDeviceDetails.ps1 -DeviceId 'device-guid' -AppId 'your-app-id' -TenantId 'your-tenant-id' -ClientSecret 'your-secret' + .\Get-IntuneDeviceDetails.ps1 -DeviceId 'device-guid' -ExportPath 'C:\Temp\DeviceDetails.csv' .EXAMPLE .\Get-IntuneDeviceDetails.ps1 -DeviceName 'LAPTOP-01' -ExportPath 'C:\Temp\DeviceDetails.csv' .NOTES - Requires: Microsoft.Graph PowerShell module - Requires: Entra ID App Registration with DeviceManagementManagedDevices.Read.All permission + Requires: Entra ID App Registration with the DeviceManagementManagedDevices.Read.All APPLICATION + permission (admin consent granted). + Exit Codes: + - 0: Query completed + - 1: A failure occurred #> [CmdletBinding()] # Define script parameters for credential input and query options -# These allow credentials and query parameters to be passed as command-line arguments param( [Parameter(Mandatory=$false)] [string]$AppId, - + [Parameter(Mandatory=$false)] [string]$TenantId, - + [Parameter(Mandatory=$false)] [string]$ClientSecret, - + + [Parameter(Mandatory=$false)] + [securestring]$ClientSecretSecure, + [Parameter(Mandatory=$false)] [string]$DeviceId, - + [Parameter(Mandatory=$false)] [string]$DeviceName, - + [Parameter(Mandatory=$false)] [string]$ExportPath, - + [Parameter(Mandatory=$false)] [ValidateRange(1, 10)] [int]$MaxRetries = 3, - + [Parameter(Mandatory=$false)] [ValidateRange(1, 60)] [int]$InitialDelaySeconds = 2 ) -# Check if Microsoft.Graph module is installed, and install if missing -# This module is required to interact with Microsoft Graph API -if(-not (Get-Module -Name Microsoft.Graph -ListAvailable)) -{ - try { - # Try to install for current user first (doesn't require admin privileges) - # This is the preferred method as it doesn't require elevation - Install-Module -Name Microsoft.Graph -Repository PSGallery -Scope CurrentUser -Force -AllowClobber -SkipPublisherCheck -ErrorAction Stop - Write-Host "Microsoft.Graph module installed successfully for current user." -ForegroundColor Green - } - catch [Exception] { - # If user-scope installation fails, try system-wide installation - # This requires administrator privileges - Write-Warning "Failed to install module for current user: $($_.Exception.Message)" - Write-Host "Attempting system-wide installation (requires admin privileges)..." -ForegroundColor Yellow - try { - Install-Module -Name Microsoft.Graph -Repository PSGallery -Force -AllowClobber -SkipPublisherCheck -ErrorAction Stop - Write-Host "Microsoft.Graph module installed successfully system-wide." -ForegroundColor Green - } - catch { - # If both installation methods fail, exit with error - Write-Error "Failed to install Microsoft.Graph module: $($_.Exception.Message)" - exit 1 - } - } +# Shared Graph helpers: token request, retry, paging, OData escaping, CSV safety +try { + Import-Module (Join-Path $PSScriptRoot '..\Common\IntuneCommon.psd1') -ErrorAction Stop } - -# Import the Microsoft Graph PowerShell module into the current session -# This makes the Graph API cmdlets available for use -try{ - Import-Module -Name Microsoft.Graph -}catch [Exception] { - # Display error message if import fails - Write-Error "Failed to import Microsoft.Graph module: $($_.Exception.Message)" +catch { + Write-Error "Failed to import the IntuneCommon module: $($_.Exception.Message)" exit 1 } -# Credential handling: Check parameters first, then environment variables -# This provides flexibility in how credentials are provided -$appid = if ($AppId) { $AppId } elseif ($env:INTUNE_APP_ID) { $env:INTUNE_APP_ID } else { '' } -$tenantid = if ($TenantId) { $TenantId } elseif ($env:INTUNE_TENANT_ID) { $env:INTUNE_TENANT_ID } else { '' } -$clientsecret = if ($ClientSecret) { $ClientSecret } elseif ($env:INTUNE_CLIENT_SECRET) { $env:INTUNE_CLIENT_SECRET } else { '' } - -# Validate that credentials are not placeholder values -# This prevents accidental use of placeholder credentials -if ($appid -match '^<.*>$' -or $tenantid -match '^<.*>$' -or $clientsecret -match '^<.*>$') { - Write-Error "Please provide valid credentials via parameters or environment variables (INTUNE_APP_ID, INTUNE_TENANT_ID, INTUNE_CLIENT_SECRET)." +# Credential handling: parameters first, then environment variables. Placeholders are rejected. +try { + $credential = Get-IntuneCredential -AppId $AppId -TenantId $TenantId -ClientSecret $ClientSecret -ClientSecretSecure $ClientSecretSecure +} +catch { + Write-Error $_.Exception.Message exit 1 } # Validate DeviceId format if provided -if ($DeviceId) { - if (-not ($DeviceId -match '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$')) { - Write-Error "DeviceId must be a valid GUID format." - exit 1 - } +if ($DeviceId -and -not (Test-GuidFormat -Guid $DeviceId)) { + Write-Error "DeviceId must be a valid GUID format." + exit 1 } -# Sanitize DeviceName input for OData query +# Escape DeviceName for an OData query: wildcard characters are removed, single quotes are doubled +$escapedDeviceName = $null if ($DeviceName) { - # Remove potentially dangerous characters from OData filter - $DeviceName = $DeviceName -replace "[';]", "" - if ([string]::IsNullOrWhiteSpace($DeviceName)) { + try { + $escapedDeviceName = Test-ODataFilterInput -InputString $DeviceName + } + catch { Write-Error "DeviceName cannot be empty after sanitization." exit 1 } @@ -143,11 +123,10 @@ if ($DeviceName) { # Validate ExportPath if provided if ($ExportPath) { - # Check if the directory exists or can be created $exportDirectory = Split-Path -Path $ExportPath -Parent if ($exportDirectory -and -not (Test-Path -Path $exportDirectory)) { try { - New-Item -Path $exportDirectory -ItemType Directory -Force | Out-Null + New-Item -Path $exportDirectory -ItemType Directory -Force -ErrorAction Stop | Out-Null Write-Verbose "Created export directory: $exportDirectory" } catch { @@ -155,8 +134,8 @@ if ($ExportPath) { exit 1 } } - - # Check if file path is writable (if file exists) or directory is writable + + # Check the file is writable if it already exists if (Test-Path -Path $ExportPath) { try { $testFile = [System.IO.File]::OpenWrite($ExportPath) @@ -169,202 +148,80 @@ if ($ExportPath) { } } +# Turn one managedDevice into a report row +function ConvertTo-DeviceDetail { + param([Parameter(Mandatory=$true)] $Device) + + [PSCustomObject][ordered]@{ + DeviceId = $Device.id + DeviceName = $Device.deviceName + UserPrincipalName = $Device.userPrincipalName + UserDisplayName = $Device.userDisplayName + EnrollmentDateTime = $Device.enrolledDateTime + LastSyncDateTime = $Device.lastSyncDateTime + ComplianceState = $Device.complianceState + ManagementAgent = $Device.managementAgent + OperatingSystem = $Device.operatingSystem + OSVersion = $Device.osVersion + Manufacturer = $Device.manufacturer + Model = $Device.model + SerialNumber = $Device.serialNumber + TotalStorageSpaceInBytes = $Device.totalStorageSpaceInBytes + FreeStorageSpaceInBytes = $Device.freeStorageSpaceInBytes + ManagedDeviceName = $Device.managedDeviceName + DeviceEnrollmentType = $Device.deviceEnrollmentType + IsSupervised = $Device.isSupervised + IsEncrypted = $Device.isEncrypted + JailBroken = $Device.jailBroken + PhoneNumber = $Device.phoneNumber + IMEI = $Device.imei + EASDeviceId = $Device.easDeviceId + ExchangeAccessState = $Device.exchangeAccessState + ExchangeAccessStateReason = $Device.exchangeAccessStateReason + } +} + # Main script execution wrapped in try-catch for error handling try { - # Import shared module for Graph API utilities - Import-Module "$PSScriptRoot\..\Common\IntuneCommon.psm1" -Force -ErrorAction Stop - - # Connect to Microsoft Graph API using app registration credentials - # This authenticates the script to access Intune data via Graph API Write-Host "Connecting to Microsoft Graph API..." -ForegroundColor Yellow - - $body = @{ - grant_type = "client_credentials" - scope = "https://graph.microsoft.com/.default" - client_id = $appid - client_secret = $clientsecret - } - - # Request an access token from Microsoft identity platform - # The token is used to authenticate subsequent Graph API requests - $tokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenantid/oauth2/v2.0/token" -Method Post -Body $body - $accessToken = $tokenResponse.access_token - - # Set up headers for Graph API requests - # The access token is included in the Authorization header - $headers = @{ - "Authorization" = "Bearer $accessToken" - "Content-Type" = "application/json" - } - + $headers = Get-IntuneGraphHeaders -AppRegistration $credential Write-Host "Successfully connected to Microsoft Graph API." -ForegroundColor Green - - # Initialize array to store device details - # This will hold all device information retrieved from Graph API - $deviceDetails = @() - - # Determine which devices to query based on provided parameters - # If DeviceId is specified, query only that device - # If DeviceName is specified, search for devices matching that name - # Otherwise, query all devices + if ($DeviceId) { Write-Host "Querying details for device: $DeviceId" -ForegroundColor Yellow - - # Query device details for specific device - # The Graph API endpoint returns comprehensive device information - $deviceUrl = "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices('$DeviceId')" - $device = Invoke-GraphApiWithRetry -Uri $deviceUrl -Headers $headers -Method Get - + + $device = Invoke-GraphApiWithRetry -Uri "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices('$DeviceId')" -Headers $headers -Method Get -MaxRetries $MaxRetries -InitialDelaySeconds $InitialDelaySeconds if ($null -eq $device) { Write-Error "Device not found or API returned null response for device ID: $DeviceId" exit 1 } - - # Create device detail object - $deviceDetail = [PSCustomObject]@{ - DeviceId = $device.id - DeviceName = $device.deviceName - UserPrincipalName = $device.userPrincipalName - UserDisplayName = $device.userDisplayName - EnrollmentDateTime = $device.enrolledDateTime - LastSyncDateTime = $device.lastSyncDateTime - ComplianceState = $device.complianceState - ManagementAgent = $device.managementAgent - OperatingSystem = $device.operatingSystem - OSVersion = $device.osVersion - Manufacturer = $device.manufacturer - Model = $device.model - SerialNumber = $device.serialNumber - TotalStorageSpaceInBytes = $device.totalStorageSpaceInBytes - FreeStorageSpaceInBytes = $device.freeStorageSpaceInBytes - ManagedDeviceName = $device.managedDeviceName - DeviceEnrollmentType = $device.deviceEnrollmentType - IsSupervised = $device.isSupervised - IsEncrypted = $device.isEncrypted - JailBroken = $device.jailBroken - PhoneNumber = $device.phoneNumber - IMEI = $device.imei - EASDeviceId = $device.easDeviceId - ExchangeAccessState = $device.exchangeAccessState - ExchangeAccessStateReason = $device.exchangeAccessStateReason - } - - $deviceDetails += $deviceDetail + $devices = @($device) } elseif ($DeviceName) { - Write-Host "Searching for devices with name: $DeviceName" -ForegroundColor Yellow - - # Query all devices and filter by name - # Filter devices by device name (supports partial matches) - $devicesUrl = "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices?`$filter=contains(deviceName,'$DeviceName')" - $devices = Invoke-GraphApiWithRetry -Uri $devicesUrl -Headers $headers -Method Get - - # Handle null or empty response - if ($null -eq $devices -or $null -eq $devices.value) { - Write-Warning "No devices found matching name: $DeviceName" - $devices = @{ value = @() } - } - - # Process each matching device - foreach ($device in $devices.value) { - $deviceDetail = [PSCustomObject]@{ - DeviceId = $device.id - DeviceName = $device.deviceName - UserPrincipalName = $device.userPrincipalName - UserDisplayName = $device.userDisplayName - EnrollmentDateTime = $device.enrolledDateTime - LastSyncDateTime = $device.lastSyncDateTime - ComplianceState = $device.complianceState - ManagementAgent = $device.managementAgent - OperatingSystem = $device.operatingSystem - OSVersion = $device.osVersion - Manufacturer = $device.manufacturer - Model = $device.model - SerialNumber = $device.serialNumber - TotalStorageSpaceInBytes = $device.totalStorageSpaceInBytes - FreeStorageSpaceInBytes = $device.freeStorageSpaceInBytes - ManagedDeviceName = $device.managedDeviceName - DeviceEnrollmentType = $device.deviceEnrollmentType - IsSupervised = $device.isSupervised - IsEncrypted = $device.isEncrypted - JailBroken = $device.jailBroken - PhoneNumber = $device.phoneNumber - IMEI = $device.imei - EASDeviceId = $device.easDeviceId - ExchangeAccessState = $device.exchangeAccessState - ExchangeAccessStateReason = $device.exchangeAccessStateReason - } - - $deviceDetails += $deviceDetail - } + Write-Host "Searching for devices whose name contains: $DeviceName" -ForegroundColor Yellow + + # Substring match. The whole filter is URL-encoded and every result page is read. + $filter = "contains(deviceName,'$escapedDeviceName')" + $devicesUrl = "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices?`$filter=$([uri]::EscapeDataString($filter))" + $devices = @(Get-GraphApiAllPages -Uri $devicesUrl -Headers $headers -MaxRetries $MaxRetries -InitialDelaySeconds $InitialDelaySeconds) + if ($devices.Count -eq 0) { Write-Warning "No devices found matching name: $DeviceName" } } else { Write-Host "Querying details for all devices..." -ForegroundColor Yellow - - # Query all managed devices from Intune - $devicesUrl = "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices" - $devices = Invoke-GraphApiWithRetry -Uri $devicesUrl -Headers $headers -Method Get - - # Handle pagination - $allDevices = @() - if ($null -ne $devices -and $null -ne $devices.value) { - $allDevices += $devices.value - } - $pageCount = 1 - while ($null -ne $devices -and $null -ne $devices.'@odata.nextLink') { - $pageCount++ - Write-Progress -Activity "Retrieving devices" -Status "Fetching page $pageCount" -PercentComplete -1 - $devices = Invoke-GraphApiWithRetry -Uri $devices.'@odata.nextLink' -Headers $headers -Method Get - if ($null -ne $devices -and $null -ne $devices.value) { - $allDevices += $devices.value - } - } - Write-Progress -Activity "Retrieving devices" -Completed - - # Process each device - foreach ($device in $allDevices) { - $deviceDetail = [PSCustomObject]@{ - DeviceId = $device.id - DeviceName = $device.deviceName - UserPrincipalName = $device.userPrincipalName - UserDisplayName = $device.userDisplayName - EnrollmentDateTime = $device.enrolledDateTime - LastSyncDateTime = $device.lastSyncDateTime - ComplianceState = $device.complianceState - ManagementAgent = $device.managementAgent - OperatingSystem = $device.operatingSystem - OSVersion = $device.osVersion - Manufacturer = $device.manufacturer - Model = $device.model - SerialNumber = $device.serialNumber - TotalStorageSpaceInBytes = $device.totalStorageSpaceInBytes - FreeStorageSpaceInBytes = $device.freeStorageSpaceInBytes - ManagedDeviceName = $device.managedDeviceName - DeviceEnrollmentType = $device.deviceEnrollmentType - IsSupervised = $device.isSupervised - IsEncrypted = $device.isEncrypted - JailBroken = $device.jailBroken - PhoneNumber = $device.phoneNumber - IMEI = $device.imei - EASDeviceId = $device.easDeviceId - ExchangeAccessState = $device.exchangeAccessState - ExchangeAccessStateReason = $device.exchangeAccessStateReason - } - - $deviceDetails += $deviceDetail - } + $devices = @(Get-GraphApiAllPages -Uri "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices" -Headers $headers -MaxRetries $MaxRetries -InitialDelaySeconds $InitialDelaySeconds) } - + + $deviceDetails = @($devices | ForEach-Object { ConvertTo-DeviceDetail -Device $_ }) + # Display results Write-Host "`nDevice Details:" -ForegroundColor Cyan Write-Host "===============" -ForegroundColor Cyan - + if ($deviceDetails.Count -eq 0) { Write-Host "No devices found matching the specified criteria." -ForegroundColor Yellow } else { - # Display each device's details foreach ($detail in $deviceDetails) { Write-Host "`nDevice: $($detail.DeviceName)" -ForegroundColor Green Write-Host " Device ID: $($detail.DeviceId)" -ForegroundColor White @@ -375,7 +232,7 @@ try Write-Host " Serial Number: $($detail.SerialNumber)" -ForegroundColor White Write-Host " Enrollment Date: $($detail.EnrollmentDateTime)" -ForegroundColor White Write-Host " Last Sync: $($detail.LastSyncDateTime)" -ForegroundColor White - Write-Host " Compliance State: $($detail.ComplianceState)" -ForegroundColor $(if ($detail.ComplianceState -eq 'Compliant') { 'Green' } else { 'Red' }) + Write-Host " Compliance State: $($detail.ComplianceState)" -ForegroundColor $(if ($detail.ComplianceState -eq 'compliant') { 'Green' } else { 'Red' }) Write-Host " Management Agent: $($detail.ManagementAgent)" -ForegroundColor White Write-Host " Enrollment Type: $($detail.DeviceEnrollmentType)" -ForegroundColor White Write-Host " Supervised: $($detail.IsSupervised)" -ForegroundColor White @@ -386,50 +243,39 @@ try Write-Host " Storage: $freeGB GB free of $totalGB GB total" -ForegroundColor White } } - + # Export to CSV if path is specified if ($ExportPath) { - # Create directory if it doesn't exist - $exportDirectory = Split-Path -Path $ExportPath -Parent - if ($exportDirectory -and -not (Test-Path -Path $exportDirectory)) { - New-Item -Path $exportDirectory -ItemType Directory -Force | Out-Null - } - - # Export results to CSV file - $deviceDetails | Export-Csv -Path $ExportPath -NoTypeInformation -Encoding UTF8 + $deviceDetails | ConvertTo-SafeCsvRecord | Export-Csv -Path $ExportPath -NoTypeInformation -Encoding UTF8 Write-Host "`nResults exported to: $ExportPath" -ForegroundColor Green - - # Verify the export file was created successfully + if (-not (Test-Path -Path $ExportPath)) { Write-Error "Export file was not created successfully at: $ExportPath" exit 1 } } } - + Write-Host "`nQuery completed successfully. Found $($deviceDetails.Count) device(s)." -ForegroundColor Green } # Error handling block - catches exceptions during Graph API calls catch { - # Capture and display the error message with script name for context $errMsg = $_.Exception.Message Write-Error "Get-IntuneDeviceDetails: Failed to retrieve device details - $errMsg" - - # Provide additional error context if available + if ($_.Exception.Response) { $statusCode = $_.Exception.Response.StatusCode.value__ Write-Verbose "HTTP Status Code: $statusCode" } - + if ($_.Exception.InnerException) { Write-Verbose "Inner Exception: $($_.Exception.InnerException.Message)" } - + if ($PSBoundParameters.ContainsKey('Verbose')) { Write-Verbose "Stack Trace: $($_.ScriptStackTrace)" } - + exit 1 } - diff --git a/Reporting/Get-IntuneDeviceHealth.ps1 b/Reporting/Get-IntuneDeviceHealth.ps1 index be9cbb5..64cee44 100644 --- a/Reporting/Get-IntuneDeviceHealth.ps1 +++ b/Reporting/Get-IntuneDeviceHealth.ps1 @@ -3,9 +3,28 @@ Comprehensive device health check. .DESCRIPTION - This script performs a comprehensive health check on Intune-managed devices including - enrollment status, sync status, connectivity, app installation status, compliance state, - and other health indicators. It can check a specific device or all devices. + This script performs a health check on Intune-managed devices covering enrollment, sync + freshness, compliance state, management agent, operating system and storage. It can check a + specific device or all devices. Every query is read through all result pages. + + Each device starts at 100 and loses points for each problem. The weights are fixed values in + this script (see $HealthWeights in Get-DeviceHealthAssessment) and are a rule of thumb, not a + Microsoft measure: + + - Not enrolled -30, never synced -25, last sync over 24 hours -20, over 8 hours -10 + - Compliance not "compliant" -15, compliance unknown -5 + - Management agent "unknown" -10, missing -5, operating system not Windows/iOS/Android/macOS -5 + - Storage over 90 percent full -15, over 80 percent -5 + + Overall health is Healthy at 90 or more, Fair at 70 or more, Warning at 50 or more, Critical below. + + The management agent list follows the Graph managementAgentType values (eas, mdm, easMdm, + intuneClient, easIntuneClient, configurationManagerClient and its co-management variants, jamf, + googleCloudDevicePolicyController, microsoft365ManagedMdm, msSense, intuneAosp). Only "unknown" + or a missing value is penalised. A device is not penalised for being enrolled for a long time. + + Graph returns 0001-01-01T00:00:00Z as the last sync of a device that has never synced. That value + is treated as "Never Synced". .PARAMETER AppId The Application (Client) ID of your Entra ID registered app. Can also be provided via @@ -15,9 +34,13 @@ Your Azure AD Tenant ID. Can also be provided via INTUNE_TENANT_ID environment variable. .PARAMETER ClientSecret - The Client Secret of your Entra ID registered app. Can also be provided via + The Client Secret of your Entra ID registered app, as plain text. A secret on the command line + ends up in shell history and process listings; prefer -ClientSecretSecure or the INTUNE_CLIENT_SECRET environment variable. +.PARAMETER ClientSecretSecure + The Client Secret as a SecureString, for example from Read-Host -AsSecureString or a vault. + .PARAMETER DeviceId Optional. The device ID to check health for. If not specified, checks all devices. @@ -25,341 +48,258 @@ Optional. Path to export results to CSV file. If not specified, results are displayed only. .EXAMPLE - .\Get-IntuneDeviceHealth.ps1 -AppId 'your-app-id' -TenantId 'your-tenant-id' -ClientSecret 'your-secret' + .\Get-IntuneDeviceHealth.ps1 -AppId 'your-app-id' -TenantId 'your-tenant-id' -ClientSecretSecure (Read-Host -AsSecureString 'Client secret') .EXAMPLE .\Get-IntuneDeviceHealth.ps1 -DeviceId 'device-guid' -ExportPath 'C:\Temp\DeviceHealth.csv' .NOTES - Requires: Microsoft.Graph PowerShell module - Requires: Entra ID App Registration with DeviceManagementManagedDevices.Read.All permission + Requires: Entra ID App Registration with the DeviceManagementManagedDevices.Read.All APPLICATION + permission (admin consent granted). + Exit Codes: + - 0: Health check completed + - 1: A failure occurred #> [CmdletBinding()] # Define script parameters for credential input and query options -# These allow credentials and query parameters to be passed as command-line arguments param( [Parameter(Mandatory=$false)] [string]$AppId, - + [Parameter(Mandatory=$false)] [string]$TenantId, - + [Parameter(Mandatory=$false)] [string]$ClientSecret, - + + [Parameter(Mandatory=$false)] + [securestring]$ClientSecretSecure, + [Parameter(Mandatory=$false)] [string]$DeviceId, - + [Parameter(Mandatory=$false)] [string]$ExportPath ) -# Check if Microsoft.Graph module is installed, and install if missing -# This module is required to interact with Microsoft Graph API -if(-not (Get-Module -Name Microsoft.Graph -ListAvailable)) -{ - try { - # Try to install for current user first (doesn't require admin privileges) - # This is the preferred method as it doesn't require elevation - Install-Module -Name Microsoft.Graph -Repository PSGallery -Scope CurrentUser -Force -AllowClobber -SkipPublisherCheck -ErrorAction Stop - Write-Host "Microsoft.Graph module installed successfully for current user." -ForegroundColor Green - } - catch [Exception] { - # If user-scope installation fails, try system-wide installation - # This requires administrator privileges - Write-Warning "Failed to install module for current user: $($_.Exception.Message)" - Write-Host "Attempting system-wide installation (requires admin privileges)..." -ForegroundColor Yellow - try { - Install-Module -Name Microsoft.Graph -Repository PSGallery -Force -AllowClobber -SkipPublisherCheck -ErrorAction Stop - Write-Host "Microsoft.Graph module installed successfully system-wide." -ForegroundColor Green - } - catch { - # If both installation methods fail, exit with error - Write-Error "Failed to install Microsoft.Graph module: $($_.Exception.Message)" - exit 1 - } - } +# Shared Graph helpers: token request, retry, paging, CSV safety +try { + Import-Module (Join-Path $PSScriptRoot '..\Common\IntuneCommon.psd1') -ErrorAction Stop } - -# Import the Microsoft Graph PowerShell module into the current session -# This makes the Graph API cmdlets available for use -try{ - Import-Module -Name Microsoft.Graph -}catch [Exception] { - # Display error message if import fails - Write-Error "Failed to import Microsoft.Graph module: $($_.Exception.Message)" +catch { + Write-Error "Failed to import the IntuneCommon module: $($_.Exception.Message)" exit 1 } -# Credential handling: Check parameters first, then environment variables -# This provides flexibility in how credentials are provided -$appid = if ($AppId) { $AppId } elseif ($env:INTUNE_APP_ID) { $env:INTUNE_APP_ID } else { '' } -$tenantid = if ($TenantId) { $TenantId } elseif ($env:INTUNE_TENANT_ID) { $env:INTUNE_TENANT_ID } else { '' } -$clientsecret = if ($ClientSecret) { $ClientSecret } elseif ($env:INTUNE_CLIENT_SECRET) { $env:INTUNE_CLIENT_SECRET } else { '' } - -# Validate that credentials are not placeholder values -# This prevents accidental use of placeholder credentials -if ($appid -match '^<.*>$' -or $tenantid -match '^<.*>$' -or $clientsecret -match '^<.*>$') { - Write-Error "Please provide valid credentials via parameters or environment variables (INTUNE_APP_ID, INTUNE_TENANT_ID, INTUNE_CLIENT_SECRET)." +# Credential handling: parameters first, then environment variables. Placeholders are rejected. +try { + $credential = Get-IntuneCredential -AppId $AppId -TenantId $TenantId -ClientSecret $ClientSecret -ClientSecretSecure $ClientSecretSecure +} +catch { + Write-Error $_.Exception.Message exit 1 } # Validate DeviceId format if provided -if ($DeviceId -and -not ($DeviceId -match '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$')) { +if ($DeviceId -and -not (Test-GuidFormat -Guid $DeviceId)) { Write-Error "DeviceId must be a valid GUID format." exit 1 } -# Main script execution wrapped in try-catch for error handling -try -{ - # Import shared module for Graph API utilities - Import-Module "$PSScriptRoot\..\Common\IntuneCommon.psm1" -Force -ErrorAction Stop +# Score one device. Pure function: the clock is a parameter so the result can be tested. +function Get-DeviceHealthAssessment { + [CmdletBinding()] + param( + [Parameter(Mandatory=$true)] + $Device, - # Connect to Microsoft Graph API using app registration credentials - # This authenticates the script to access Intune data via Graph API - Write-Host "Connecting to Microsoft Graph API..." -ForegroundColor Yellow - - $body = @{ - grant_type = "client_credentials" - scope = "https://graph.microsoft.com/.default" - client_id = $appid - client_secret = $clientsecret + [Parameter(Mandatory=$false)] + [datetime]$Now = (Get-Date) + ) + + # Points lost per problem. A rule of thumb, kept in one place. + $HealthWeights = @{ + NotEnrolled = 30; NeverSynced = 25; SyncStale = 20; SyncWarning = 10 + NotCompliant = 15; ComplianceUnknown = 5 + AgentUnknown = 10; AgentMissing = 5; OsUnsupported = 5 + StorageCritical = 15; StorageWarning = 5 } - - # Request an access token from Microsoft identity platform - # The token is used to authenticate subsequent Graph API requests - $tokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenantid/oauth2/v2.0/token" -Method Post -Body $body - $accessToken = $tokenResponse.access_token - - # Set up headers for Graph API requests - # The access token is included in the Authorization header - $headers = @{ - "Authorization" = "Bearer $accessToken" - "Content-Type" = "application/json" + + # managementAgentType values from Microsoft Graph, other than "unknown" + $knownAgents = @('eas', 'mdm', 'easMdm', 'intuneClient', 'easIntuneClient', 'configurationManagerClient', + 'configurationManagerClientMdm', 'configurationManagerClientMdmEas', 'jamf', + 'googleCloudDevicePolicyController', 'microsoft365ManagedMdm', 'msSense', 'intuneAosp') + + $healthScore = 100 + $healthIssues = @() + + # Check 1: Enrollment status + $enrollmentStatus = "Healthy" + if (-not $Device.enrolledDateTime) { + $enrollmentStatus = "Not Enrolled" + $healthScore -= $HealthWeights.NotEnrolled + $healthIssues += "Device not enrolled" } - - Write-Host "Successfully connected to Microsoft Graph API." -ForegroundColor Green - - # Initialize array to store device health results - # This will hold all device health information retrieved from Graph API - $deviceHealthResults = @() - - # Determine which devices to check - # If DeviceId is specified, check only that device - # Otherwise, check all devices - if ($DeviceId) { - Write-Host "Checking health for device: $DeviceId" -ForegroundColor Yellow - - # Query device details for specific device - # Get comprehensive device information - $deviceUrl = "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices('$DeviceId')" - $device = Invoke-GraphApiWithRetry -Uri $deviceUrl -Headers $headers -Method Get - $devices = @($device) + + # Check 2: Sync status. A device that never synced has no date or Graph's 0001-01-01 placeholder. + $syncStatus = "Healthy" + $lastSync = $null + if ($Device.lastSyncDateTime) { + $lastSync = [datetime]$Device.lastSyncDateTime + if ($lastSync.Year -le 1) { $lastSync = $null } } - else { - Write-Host "Checking health for all devices..." -ForegroundColor Yellow - - # Query all managed devices from Intune - $devicesUrl = "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices" - $devices = Invoke-GraphApiWithRetry -Uri $devicesUrl -Headers $headers -Method Get - - # Handle pagination - $allDevices = @() - if ($null -ne $devices -and $null -ne $devices.value) { - $allDevices += $devices.value + if ($null -ne $lastSync) { + $hoursSinceSync = ($Now - $lastSync).TotalHours + if ($hoursSinceSync -gt 24) { + $syncStatus = "Stale" + $healthScore -= $HealthWeights.SyncStale + $healthIssues += "Last sync was over 24 hours ago" } - $pageCount = 1 - while ($null -ne $devices -and $null -ne $devices.'@odata.nextLink') { - $pageCount++ - Write-Progress -Activity "Retrieving devices" -Status "Fetching page $pageCount" -PercentComplete -1 - $devices = Invoke-GraphApiWithRetry -Uri $devices.'@odata.nextLink' -Headers $headers -Method Get - if ($null -ne $devices -and $null -ne $devices.value) { - $allDevices += $devices.value - } + elseif ($hoursSinceSync -gt 8) { + $syncStatus = "Warning" + $healthScore -= $HealthWeights.SyncWarning + $healthIssues += "Last sync was over 8 hours ago" } - Write-Progress -Activity "Retrieving devices" -Completed - - $devices = $allDevices } - - Write-Host "Found $($devices.Count) device(s). Checking health..." -ForegroundColor Cyan - - # Process each device and perform health check - $deviceCount = 0 - foreach ($device in $devices) { - $deviceCount++ - Write-Host "Checking device $deviceCount of $($devices.Count): $($device.deviceName)" -ForegroundColor Cyan - - # Calculate health score based on various factors - $healthScore = 100 - $healthIssues = @() - - # Check 1: Enrollment status - $enrollmentStatus = "Healthy" - if (-not $device.enrolledDateTime) { - $enrollmentStatus = "Not Enrolled" - $healthScore -= 30 - $healthIssues += "Device not enrolled" - } - else { - $enrollmentAge = (Get-Date) - [DateTime]$device.enrolledDateTime - if ($enrollmentAge.Days -gt 365) { - $enrollmentStatus = "Old Enrollment" - $healthScore -= 5 - $healthIssues += "Enrollment is over 1 year old" - } - } - - # Check 2: Sync status - $syncStatus = "Healthy" - if ($device.lastSyncDateTime) { - $lastSync = [DateTime]$device.lastSyncDateTime - $timeSinceSync = (Get-Date) - $lastSync - - if ($timeSinceSync.TotalHours -gt 24) { - $syncStatus = "Stale" - $healthScore -= 20 - $healthIssues += "Last sync was over 24 hours ago" - } - elseif ($timeSinceSync.TotalHours -gt 8) { - $syncStatus = "Warning" - $healthScore -= 10 - $healthIssues += "Last sync was over 8 hours ago" - } - } - else { - $syncStatus = "Never Synced" - $healthScore -= 25 - $healthIssues += "Device has never synced" - } - - # Check 3: Compliance state - # Verify device is compliant - $complianceStatus = "Healthy" - if ($device.complianceState) { - if ($device.complianceState -ne "Compliant") { - $complianceStatus = $device.complianceState - $healthScore -= 15 - $healthIssues += "Device is not compliant: $($device.complianceState)" - } - } - else { - $complianceStatus = "Unknown" - $healthScore -= 5 - $healthIssues += "Compliance state unknown" - } - - # Check 4: Management agent - # Verify device is using a supported management agent - $managementStatus = "Healthy" - if ($device.managementAgent) { - $supportedAgents = @("MDM", "EAS", "IntuneClient") - if ($device.managementAgent -notin $supportedAgents) { - $managementStatus = "Unsupported" - $healthScore -= 10 - $healthIssues += "Unsupported management agent: $($device.managementAgent)" - } + else { + $syncStatus = "Never Synced" + $healthScore -= $HealthWeights.NeverSynced + $healthIssues += "Device has never synced" + } + + # Check 3: Compliance state + $complianceStatus = "Healthy" + if ($Device.complianceState) { + if ($Device.complianceState -ne "compliant") { + $complianceStatus = $Device.complianceState + $healthScore -= $HealthWeights.NotCompliant + $healthIssues += "Device is not compliant: $($Device.complianceState)" } - else { + } + else { + $complianceStatus = "Unknown" + $healthScore -= $HealthWeights.ComplianceUnknown + $healthIssues += "Compliance state unknown" + } + + # Check 4: Management agent + $managementStatus = "Healthy" + if ($Device.managementAgent) { + if ($Device.managementAgent -notin $knownAgents) { $managementStatus = "Unknown" - $healthScore -= 5 - $healthIssues += "Management agent unknown" + $healthScore -= $HealthWeights.AgentUnknown + $healthIssues += "Management agent is not a recognised value: $($Device.managementAgent)" } - - # Check 5: Operating system - # Verify device is running a supported OS - $osStatus = "Healthy" - if ($device.operatingSystem) { - $supportedOS = @("Windows", "iOS", "Android", "macOS") - if ($device.operatingSystem -notin $supportedOS) { - $osStatus = "Unsupported" - $healthScore -= 5 - $healthIssues += "Unsupported operating system: $($device.operatingSystem)" - } - } - - # Check 6: Storage space (if available) - # Verify device has adequate storage - $storageStatus = "Healthy" - if ($device.totalStorageSpaceInBytes -and $device.freeStorageSpaceInBytes) { - $usedPercent = (($device.totalStorageSpaceInBytes - $device.freeStorageSpaceInBytes) / $device.totalStorageSpaceInBytes) * 100 - - if ($usedPercent -gt 90) { - $storageStatus = "Critical" - $healthScore -= 15 - $healthIssues += "Storage is over 90% full" - } - elseif ($usedPercent -gt 80) { - $storageStatus = "Warning" - $healthScore -= 5 - $healthIssues += "Storage is over 80% full" - } - } - - # Determine overall health status - # Categorize health based on score - $overallHealth = "Healthy" - if ($healthScore -lt 50) { - $overallHealth = "Critical" + } + else { + $managementStatus = "Unknown" + $healthScore -= $HealthWeights.AgentMissing + $healthIssues += "Management agent missing" + } + + # Check 5: Operating system + $osStatus = "Healthy" + if ($Device.operatingSystem) { + if ($Device.operatingSystem -notin @("Windows", "iOS", "Android", "macOS")) { + $osStatus = "Unsupported" + $healthScore -= $HealthWeights.OsUnsupported + $healthIssues += "Unsupported operating system: $($Device.operatingSystem)" } - elseif ($healthScore -lt 70) { - $overallHealth = "Warning" + } + + # Check 6: Storage space (if available) + $storageStatus = "Healthy" + if ($Device.totalStorageSpaceInBytes -and $Device.freeStorageSpaceInBytes) { + $usedPercent = (($Device.totalStorageSpaceInBytes - $Device.freeStorageSpaceInBytes) / $Device.totalStorageSpaceInBytes) * 100 + if ($usedPercent -gt 90) { + $storageStatus = "Critical" + $healthScore -= $HealthWeights.StorageCritical + $healthIssues += "Storage is over 90% full" } - elseif ($healthScore -lt 90) { - $overallHealth = "Fair" + elseif ($usedPercent -gt 80) { + $storageStatus = "Warning" + $healthScore -= $HealthWeights.StorageWarning + $healthIssues += "Storage is over 80% full" } - - # Create device health result object - $deviceHealth = [PSCustomObject]@{ - DeviceId = $device.id - DeviceName = $device.deviceName - UserPrincipalName = $device.userPrincipalName - OverallHealth = $overallHealth - HealthScore = $healthScore - EnrollmentStatus = $enrollmentStatus - EnrollmentDate = $device.enrolledDateTime - SyncStatus = $syncStatus - LastSyncDateTime = $device.lastSyncDateTime - ComplianceStatus = $complianceStatus - ComplianceState = $device.complianceState - ManagementStatus = $managementStatus - ManagementAgent = $device.managementAgent - OSStatus = $osStatus - OperatingSystem = $device.operatingSystem - OSVersion = $device.osVersion - StorageStatus = $storageStatus - TotalStorageGB = if ($device.totalStorageSpaceInBytes) { [math]::Round($device.totalStorageSpaceInBytes / 1GB, 2) } else { $null } - FreeStorageGB = if ($device.freeStorageSpaceInBytes) { [math]::Round($device.freeStorageSpaceInBytes / 1GB, 2) } else { $null } - HealthIssues = ($healthIssues -join '; ') - HealthIssueCount = $healthIssues.Count + } + + $overallHealth = "Healthy" + if ($healthScore -lt 50) { $overallHealth = "Critical" } + elseif ($healthScore -lt 70) { $overallHealth = "Warning" } + elseif ($healthScore -lt 90) { $overallHealth = "Fair" } + + [PSCustomObject][ordered]@{ + DeviceId = $Device.id + DeviceName = $Device.deviceName + UserPrincipalName = $Device.userPrincipalName + OverallHealth = $overallHealth + HealthScore = $healthScore + EnrollmentStatus = $enrollmentStatus + EnrollmentDate = $Device.enrolledDateTime + SyncStatus = $syncStatus + LastSyncDateTime = $Device.lastSyncDateTime + ComplianceStatus = $complianceStatus + ComplianceState = $Device.complianceState + ManagementStatus = $managementStatus + ManagementAgent = $Device.managementAgent + OSStatus = $osStatus + OperatingSystem = $Device.operatingSystem + OSVersion = $Device.osVersion + StorageStatus = $storageStatus + TotalStorageGB = if ($Device.totalStorageSpaceInBytes) { [math]::Round($Device.totalStorageSpaceInBytes / 1GB, 2) } else { $null } + FreeStorageGB = if ($Device.freeStorageSpaceInBytes) { [math]::Round($Device.freeStorageSpaceInBytes / 1GB, 2) } else { $null } + HealthIssues = ($healthIssues -join '; ') + HealthIssueCount = $healthIssues.Count + } +} + +# Main script execution wrapped in try-catch for error handling +try +{ + Write-Host "Connecting to Microsoft Graph API..." -ForegroundColor Yellow + $headers = Get-IntuneGraphHeaders -AppRegistration $credential + Write-Host "Successfully connected to Microsoft Graph API." -ForegroundColor Green + + if ($DeviceId) { + Write-Host "Checking health for device: $DeviceId" -ForegroundColor Yellow + + $device = Invoke-GraphApiWithRetry -Uri "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices('$DeviceId')" -Headers $headers -Method Get + if ($null -eq $device) { + Write-Error "Device not found or API returned null response for device ID: $DeviceId" + exit 1 } - - $deviceHealthResults += $deviceHealth + $devices = @($device) } - + else { + Write-Host "Checking health for all devices..." -ForegroundColor Yellow + $devices = @(Get-GraphApiAllPages -Uri "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices" -Headers $headers) + } + + Write-Host "Found $($devices.Count) device(s). Checking health..." -ForegroundColor Cyan + + $now = Get-Date + $deviceHealthResults = @($devices | ForEach-Object { Get-DeviceHealthAssessment -Device $_ -Now $now }) + # Display results Write-Host "`nDevice Health Results:" -ForegroundColor Cyan Write-Host "=====================" -ForegroundColor Cyan - + if ($deviceHealthResults.Count -eq 0) { Write-Host "No devices found matching the specified criteria." -ForegroundColor Yellow } else { - # Group results by health status for better display - $healthyDevices = $deviceHealthResults | Where-Object { $_.OverallHealth -eq "Healthy" } - $fairDevices = $deviceHealthResults | Where-Object { $_.OverallHealth -eq "Fair" } - $warningDevices = $deviceHealthResults | Where-Object { $_.OverallHealth -eq "Warning" } - $criticalDevices = $deviceHealthResults | Where-Object { $_.OverallHealth -eq "Critical" } - + $healthyDevices = @($deviceHealthResults | Where-Object { $_.OverallHealth -eq "Healthy" }) + $fairDevices = @($deviceHealthResults | Where-Object { $_.OverallHealth -eq "Fair" }) + $warningDevices = @($deviceHealthResults | Where-Object { $_.OverallHealth -eq "Warning" }) + $criticalDevices = @($deviceHealthResults | Where-Object { $_.OverallHealth -eq "Critical" }) + Write-Host "`nHealth Summary:" -ForegroundColor Cyan Write-Host " Healthy: $($healthyDevices.Count)" -ForegroundColor Green Write-Host " Fair: $($fairDevices.Count)" -ForegroundColor Yellow Write-Host " Warning: $($warningDevices.Count)" -ForegroundColor $(if ($warningDevices.Count -gt 0) { 'Yellow' } else { 'White' }) Write-Host " Critical: $($criticalDevices.Count)" -ForegroundColor $(if ($criticalDevices.Count -gt 0) { 'Red' } else { 'White' }) - - # Display each device's health + foreach ($health in $deviceHealthResults) { $healthColor = switch ($health.OverallHealth) { "Healthy" { "Green" } @@ -368,7 +308,7 @@ try "Critical" { "Red" } default { "White" } } - + Write-Host "`nDevice: $($health.DeviceName)" -ForegroundColor $healthColor Write-Host " Overall Health: $($health.OverallHealth) (Score: $($health.HealthScore))" -ForegroundColor $healthColor Write-Host " User: $($health.UserPrincipalName)" -ForegroundColor White @@ -383,50 +323,44 @@ try } } } - + # Export to CSV if path is specified if ($ExportPath) { - # Create directory if it doesn't exist $exportDirectory = Split-Path -Path $ExportPath -Parent if ($exportDirectory -and -not (Test-Path -Path $exportDirectory)) { New-Item -Path $exportDirectory -ItemType Directory -Force | Out-Null } - - # Export results to CSV file - $deviceHealthResults | Export-Csv -Path $ExportPath -NoTypeInformation -Encoding UTF8 + + $deviceHealthResults | ConvertTo-SafeCsvRecord | Export-Csv -Path $ExportPath -NoTypeInformation -Encoding UTF8 Write-Host "`nResults exported to: $ExportPath" -ForegroundColor Green - - # Verify the export file was created successfully + if (-not (Test-Path -Path $ExportPath)) { Write-Error "Export file was not created successfully at: $ExportPath" exit 1 } } } - + Write-Host "`nHealth check completed successfully. Checked $($deviceHealthResults.Count) device(s)." -ForegroundColor Green } # Error handling block - catches exceptions during Graph API calls catch { - # Capture and display the error message with script name for context $errMsg = $_.Exception.Message Write-Error "Get-IntuneDeviceHealth: Failed to check device health - $errMsg" - - # Provide additional error context if available + if ($_.Exception.Response) { $statusCode = $_.Exception.Response.StatusCode.value__ Write-Verbose "HTTP Status Code: $statusCode" } - + if ($_.Exception.InnerException) { Write-Verbose "Inner Exception: $($_.Exception.InnerException.Message)" } - + if ($PSBoundParameters.ContainsKey('Verbose')) { Write-Verbose "Stack Trace: $($_.ScriptStackTrace)" } - + exit 1 } - diff --git a/Reporting/Get-IntunePolicyAssignments.ps1 b/Reporting/Get-IntunePolicyAssignments.ps1 index 7f5d3c4..1efb035 100644 --- a/Reporting/Get-IntunePolicyAssignments.ps1 +++ b/Reporting/Get-IntunePolicyAssignments.ps1 @@ -5,7 +5,12 @@ .DESCRIPTION This script connects to Microsoft Graph API and retrieves all Intune policy assignments including configuration profiles and compliance policies. It shows which policies are - assigned to which groups or users, assignment filters, and assignment intent. + assigned to which groups or users and the assignment intent. + + A policy with no assignments gets one row with TargetType "None" and TargetName + "No assignments", so unassigned policies show up in the report. A policy whose assignments + could not be read gets one row with TargetType "Error". If any policy has an error row the + script exits 1 at the end, so an incomplete report is not mistaken for a complete one. .PARAMETER AppId The Application (Client) ID of your Entra ID registered app. Can also be provided via @@ -15,9 +20,13 @@ Your Azure AD Tenant ID. Can also be provided via INTUNE_TENANT_ID environment variable. .PARAMETER ClientSecret - The Client Secret of your Entra ID registered app. Can also be provided via + The Client Secret of your Entra ID registered app, as plain text. A secret on the command line + ends up in shell history and process listings; prefer -ClientSecretSecure or the INTUNE_CLIENT_SECRET environment variable. +.PARAMETER ClientSecretSecure + The Client Secret as a SecureString, for example from Read-Host -AsSecureString or a vault. + .PARAMETER PolicyType Optional. Filter by policy type: "Configuration" or "Compliance". If not specified, retrieves both. @@ -25,436 +34,241 @@ Optional. Path to export results to CSV file. If not specified, results are displayed only. .EXAMPLE - .\Get-IntunePolicyAssignments.ps1 -AppId 'your-app-id' -TenantId 'your-tenant-id' -ClientSecret 'your-secret' + .\Get-IntunePolicyAssignments.ps1 -AppId 'your-app-id' -TenantId 'your-tenant-id' -ClientSecretSecure (Read-Host -AsSecureString 'Client secret') .EXAMPLE + $env:INTUNE_APP_ID = 'your-app-id'; $env:INTUNE_TENANT_ID = 'your-tenant-id'; $env:INTUNE_CLIENT_SECRET = '' .\Get-IntunePolicyAssignments.ps1 -PolicyType "Configuration" -ExportPath 'C:\Temp\PolicyAssignments.csv' .NOTES - Requires: Microsoft.Graph PowerShell module - Requires: Entra ID App Registration with DeviceManagementConfiguration.Read.All permission + Requires: Entra ID App Registration with the DeviceManagementConfiguration.Read.All APPLICATION + permission (admin consent granted) and Group.Read.All to resolve group names. + Exit Codes: + - 0: Report complete + - 1: A failure, or at least one policy's assignments could not be retrieved #> [CmdletBinding()] # Define script parameters for credential input and query options -# These allow credentials and query parameters to be passed as command-line arguments param( [Parameter(Mandatory=$false)] [string]$AppId, - + [Parameter(Mandatory=$false)] [string]$TenantId, - + [Parameter(Mandatory=$false)] [string]$ClientSecret, - + + [Parameter(Mandatory=$false)] + [securestring]$ClientSecretSecure, + [Parameter(Mandatory=$false)] [ValidateSet("Configuration", "Compliance", "All")] [string]$PolicyType = "All", - + [Parameter(Mandatory=$false)] [string]$ExportPath ) -# Check if Microsoft.Graph module is installed, and install if missing -# This module is required to interact with Microsoft Graph API -if(-not (Get-Module -Name Microsoft.Graph -ListAvailable)) -{ +# Shared Graph helpers: token request, retry, paging, CSV safety +try { + Import-Module (Join-Path $PSScriptRoot '..\Common\IntuneCommon.psd1') -ErrorAction Stop +} +catch { + Write-Error "Failed to import the IntuneCommon module: $($_.Exception.Message)" + exit 1 +} + +# Credential handling: parameters first, then environment variables. Placeholders are rejected. +try { + $credential = Get-IntuneCredential -AppId $AppId -TenantId $TenantId -ClientSecret $ClientSecret -ClientSecretSecure $ClientSecretSecure +} +catch { + Write-Error $_.Exception.Message + exit 1 +} + +# Resolve a group ID to its display name. Cached so each group is looked up once. +# A failed lookup falls back to the group ID; the assignment itself is still reported. +$script:groupNameCache = @{} +function Resolve-GroupName { + param([string]$GroupId) + + if ($script:groupNameCache.ContainsKey($GroupId)) { return $script:groupNameCache[$GroupId] } + + $name = $GroupId try { - # Try to install for current user first (doesn't require admin privileges) - # This is the preferred method as it doesn't require elevation - Install-Module -Name Microsoft.Graph -Repository PSGallery -Scope CurrentUser -Force -AllowClobber -SkipPublisherCheck -ErrorAction Stop - Write-Host "Microsoft.Graph module installed successfully for current user." -ForegroundColor Green + $group = Invoke-GraphApiWithRetry -Uri "https://graph.microsoft.com/v1.0/groups/$GroupId" -Headers $script:headers -Method Get + if ($null -ne $group -and $null -ne $group.displayName) { $name = $group.displayName } } - catch [Exception] { - # If user-scope installation fails, try system-wide installation - # This requires administrator privileges - Write-Warning "Failed to install module for current user: $($_.Exception.Message)" - Write-Host "Attempting system-wide installation (requires admin privileges)..." -ForegroundColor Yellow - try { - Install-Module -Name Microsoft.Graph -Repository PSGallery -Force -AllowClobber -SkipPublisherCheck -ErrorAction Stop - Write-Host "Microsoft.Graph module installed successfully system-wide." -ForegroundColor Green - } - catch { - # If both installation methods fail, exit with error - Write-Error "Failed to install Microsoft.Graph module: $($_.Exception.Message)" - exit 1 - } + catch { + Write-Verbose "Failed to retrieve group name for Group ID: $GroupId - $($_.Exception.Message)" } + $script:groupNameCache[$GroupId] = $name + return $name } -# Import the Microsoft Graph PowerShell module into the current session -# This makes the Graph API cmdlets available for use -try{ - Import-Module -Name Microsoft.Graph -}catch [Exception] { - # Display error message if import fails - Write-Error "Failed to import Microsoft.Graph module: $($_.Exception.Message)" - exit 1 -} +# Build the report rows for one policy. Always returns at least one row: +# the assignments, a "No assignments" row, or an "Error" row. +function Get-PolicyAssignmentRow { + param( + [Parameter(Mandatory=$true)] [string]$Type, + [Parameter(Mandatory=$true)] $Policy, + [Parameter(Mandatory=$true)] [string]$AssignmentsUrl + ) -# Credential handling: Check parameters first, then environment variables -# This provides flexibility in how credentials are provided -$appid = if ($AppId) { $AppId } elseif ($env:INTUNE_APP_ID) { $env:INTUNE_APP_ID } else { '' } -$tenantid = if ($TenantId) { $TenantId } elseif ($env:INTUNE_TENANT_ID) { $env:INTUNE_TENANT_ID } else { '' } -$clientsecret = if ($ClientSecret) { $ClientSecret } elseif ($env:INTUNE_CLIENT_SECRET) { $env:INTUNE_CLIENT_SECRET } else { '' } + # Column order is fixed here so the CSV always has the same columns in the same order + function Get-PolicyRow($AssignmentId, $TargetType, $TargetId, $TargetName, $Intent, $Source) { + [PSCustomObject][ordered]@{ + PolicyType = $Type + PolicyId = $Policy.id + PolicyName = $Policy.displayName + PolicyDescription = $Policy.description + AssignmentId = $AssignmentId + TargetType = $TargetType + TargetId = $TargetId + TargetName = $TargetName + Intent = $Intent + Source = $Source + } + } -# Validate that credentials are not placeholder values -# This prevents accidental use of placeholder credentials -if ($appid -match '^<.*>$' -or $tenantid -match '^<.*>$' -or $clientsecret -match '^<.*>$') { - Write-Error "Please provide valid credentials via parameters or environment variables (INTUNE_APP_ID, INTUNE_TENANT_ID, INTUNE_CLIENT_SECRET)." - exit 1 + try { + # Count the list, not $null: an empty list parses as an empty array, never as $null + $assignments = @(Get-GraphApiAllPages -Uri $AssignmentsUrl -Headers $script:headers) + } + catch { + Write-Verbose "Failed to retrieve assignments for $Type policy '$($Policy.displayName)': $($_.Exception.Message)" + $script:assignmentErrorCount++ + return (Get-PolicyRow $null "Error" $null "Error retrieving assignments: $($_.Exception.Message)" $null $null) + } + + if ($assignments.Count -eq 0) { + return (Get-PolicyRow $null "None" $null "No assignments" $null $null) + } + + foreach ($assignment in $assignments) { + $targetGroupId = $assignment.target.groupId + $targetName = $assignment.target.'@odata.type' + if ($targetGroupId) { $targetName = Resolve-GroupName -GroupId $targetGroupId } + + Get-PolicyRow $assignment.id $assignment.target.'@odata.type' $targetGroupId $targetName $assignment.intent $assignment.source + } } # Main script execution wrapped in try-catch for error handling try { - # Import shared module for Graph API utilities - Import-Module "$PSScriptRoot\..\Common\IntuneCommon.psm1" -Force -ErrorAction Stop - - # Connect to Microsoft Graph API using app registration credentials - # This authenticates the script to access Intune data via Graph API Write-Host "Connecting to Microsoft Graph API..." -ForegroundColor Yellow - - $body = @{ - grant_type = "client_credentials" - scope = "https://graph.microsoft.com/.default" - client_id = $appid - client_secret = $clientsecret - } - - # Request an access token from Microsoft identity platform - # The token is used to authenticate subsequent Graph API requests - $tokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenantid/oauth2/v2.0/token" -Method Post -Body $body - $accessToken = $tokenResponse.access_token - - # Set up headers for Graph API requests - # The access token is included in the Authorization header - $headers = @{ - "Authorization" = "Bearer $accessToken" - "Content-Type" = "application/json" - } - + $script:headers = Get-IntuneGraphHeaders -AppRegistration $credential Write-Host "Successfully connected to Microsoft Graph API." -ForegroundColor Green - - # Initialize array to store policy assignment results + + $script:assignmentErrorCount = 0 $policyAssignments = @() - - # Query configuration profiles if requested + # Configuration profiles define device settings and restrictions if ($PolicyType -eq "All" -or $PolicyType -eq "Configuration") { Write-Host "`nQuerying configuration profiles..." -ForegroundColor Yellow - - # Query all configuration profiles from Intune - $configProfilesUrl = "https://graph.microsoft.com/v1.0/deviceManagement/deviceConfigurations" - $configProfiles = Invoke-GraphApiWithRetry -Uri $configProfilesUrl -Headers $headers -Method Get - - # Handle null or empty response - $allConfigProfiles = @() - if ($null -ne $configProfiles -and $null -ne $configProfiles.value) { - $allConfigProfiles += $configProfiles.value - } - $pageCount = 1 - - # Check if there are more pages of results - while ($null -ne $configProfiles -and $null -ne $configProfiles.'@odata.nextLink') { - $pageCount++ - Write-Progress -Activity "Retrieving configuration profiles" -Status "Fetching page $pageCount" -PercentComplete -1 - $configProfiles = Invoke-GraphApiWithRetry -Uri $configProfiles.'@odata.nextLink' -Headers $headers -Method Get - if ($null -ne $configProfiles -and $null -ne $configProfiles.value) { - $allConfigProfiles += $configProfiles.value - } - } - Write-Progress -Activity "Retrieving configuration profiles" -Completed - - # Process each configuration profile + $allConfigProfiles = @(Get-GraphApiAllPages -Uri "https://graph.microsoft.com/v1.0/deviceManagement/deviceConfigurations" -Headers $script:headers) + $profileCount = 0 foreach ($configProfile in $allConfigProfiles) { $profileCount++ Write-Progress -Activity "Processing configuration profiles" -Status "Processing profile $profileCount of $($allConfigProfiles.Count): $($configProfile.displayName)" -PercentComplete (($profileCount / $allConfigProfiles.Count) * 100) Write-Host " Processing configuration profile: $($configProfile.displayName)" -ForegroundColor Cyan - - # Get assignments for this configuration profile - $assignmentsUrl = "https://graph.microsoft.com/v1.0/deviceManagement/deviceConfigurations('$($configProfile.id)')/assignments" - try { - $assignments = Invoke-GraphApiWithRetry -Uri $assignmentsUrl -Headers $headers -Method Get - - # Handle null or empty response - if ($null -eq $assignments -or $null -eq $assignments.value) { - # No assignments found, create entry with no assignments - $policyAssignment = [PSCustomObject]@{ - PolicyType = "Configuration" - PolicyId = $configProfile.id - PolicyName = $configProfile.displayName - PolicyDescription = $configProfile.description - AssignmentId = $null - TargetType = "None" - TargetId = $null - TargetName = "No assignments" - Intent = $null - Source = $null - } - $policyAssignments += $policyAssignment - continue - } - - foreach ($assignment in $assignments.value) { - # Get target group information - $targetGroupId = $assignment.target.groupId - $targetName = $assignment.target.'@odata.type' - - # Resolve group name if it's a group assignment - if ($targetGroupId) { - try { - $groupUrl = "https://graph.microsoft.com/v1.0/groups/$targetGroupId" - $group = Invoke-GraphApiWithRetry -Uri $groupUrl -Headers $headers -Method Get - if ($null -ne $group -and $null -ne $group.displayName) { - $targetName = $group.displayName - } - else { - $targetName = $targetGroupId - Write-Verbose "Could not retrieve group name for Group ID: $targetGroupId" - } - } - catch { - $targetName = $targetGroupId - Write-Verbose "Failed to retrieve group name for Group ID: $targetGroupId - $($_.Exception.Message)" - } - } - - # Create policy assignment object - $policyAssignment = [PSCustomObject]@{ - PolicyType = "Configuration" - PolicyId = $configProfile.id - PolicyName = $configProfile.displayName - PolicyDescription = $configProfile.description - AssignmentId = $assignment.id - TargetType = $assignment.target.'@odata.type' - TargetId = $targetGroupId - TargetName = $targetName - Intent = $assignment.intent - Source = $assignment.source - } - - $policyAssignments += $policyAssignment - } - } - catch { - # If API call failed, create entry with error information - Write-Verbose "Failed to retrieve assignments for configuration profile '$($configProfile.displayName)': $($_.Exception.Message)" - $policyAssignment = [PSCustomObject]@{ - PolicyType = "Configuration" - PolicyId = $configProfile.id - PolicyName = $configProfile.displayName - PolicyDescription = $configProfile.description - AssignmentId = $null - TargetType = "Error" - TargetId = $null - TargetName = "Error retrieving assignments: $($_.Exception.Message)" - Intent = $null - Source = $null - } - - $policyAssignments += $policyAssignment - } + + $url = "https://graph.microsoft.com/v1.0/deviceManagement/deviceConfigurations('$($configProfile.id)')/assignments" + $policyAssignments += @(Get-PolicyAssignmentRow -Type "Configuration" -Policy $configProfile -AssignmentsUrl $url) } Write-Progress -Activity "Processing configuration profiles" -Completed } - - # Query compliance policies if requested + # Compliance policies define requirements devices must meet if ($PolicyType -eq "All" -or $PolicyType -eq "Compliance") { Write-Host "`nQuerying compliance policies..." -ForegroundColor Yellow - - # Query all compliance policies from Intune - $compliancePoliciesUrl = "https://graph.microsoft.com/v1.0/deviceManagement/deviceCompliancePolicies" - $compliancePolicies = Invoke-GraphApiWithRetry -Uri $compliancePoliciesUrl -Headers $headers -Method Get - - # Handle null or empty response - $allCompliancePolicies = @() - if ($null -ne $compliancePolicies -and $null -ne $compliancePolicies.value) { - $allCompliancePolicies += $compliancePolicies.value - } - $pageCount = 1 - - # Check if there are more pages of results - while ($null -ne $compliancePolicies -and $null -ne $compliancePolicies.'@odata.nextLink') { - $pageCount++ - Write-Progress -Activity "Retrieving compliance policies" -Status "Fetching page $pageCount" -PercentComplete -1 - $compliancePolicies = Invoke-GraphApiWithRetry -Uri $compliancePolicies.'@odata.nextLink' -Headers $headers -Method Get - if ($null -ne $compliancePolicies -and $null -ne $compliancePolicies.value) { - $allCompliancePolicies += $compliancePolicies.value - } - } - Write-Progress -Activity "Retrieving compliance policies" -Completed - - # Process each compliance policy and get its assignments + $allCompliancePolicies = @(Get-GraphApiAllPages -Uri "https://graph.microsoft.com/v1.0/deviceManagement/deviceCompliancePolicies" -Headers $script:headers) + $policyCount = 0 foreach ($policy in $allCompliancePolicies) { $policyCount++ Write-Progress -Activity "Processing compliance policies" -Status "Processing policy $policyCount of $($allCompliancePolicies.Count): $($policy.displayName)" -PercentComplete (($policyCount / $allCompliancePolicies.Count) * 100) Write-Host " Processing compliance policy: $($policy.displayName)" -ForegroundColor Cyan - - # Get assignments for this compliance policy - $assignmentsUrl = "https://graph.microsoft.com/v1.0/deviceManagement/deviceCompliancePolicies('$($policy.id)')/assignments" - try { - $assignments = Invoke-GraphApiWithRetry -Uri $assignmentsUrl -Headers $headers -Method Get - - # Handle null or empty response - if ($null -eq $assignments -or $null -eq $assignments.value) { - # No assignments found, create entry with no assignments - $policyAssignment = [PSCustomObject]@{ - PolicyType = "Compliance" - PolicyId = $policy.id - PolicyName = $policy.displayName - PolicyDescription = $policy.description - AssignmentId = $null - TargetType = "None" - TargetId = $null - TargetName = "No assignments" - Intent = $null - Source = $null - } - $policyAssignments += $policyAssignment - continue - } - - foreach ($assignment in $assignments.value) { - # Get target group information - $targetGroupId = $assignment.target.groupId - $targetName = $assignment.target.'@odata.type' - - # Resolve group name if it's a group assignment - if ($targetGroupId) { - try { - $groupUrl = "https://graph.microsoft.com/v1.0/groups/$targetGroupId" - $group = Invoke-GraphApiWithRetry -Uri $groupUrl -Headers $headers -Method Get - if ($null -ne $group -and $null -ne $group.displayName) { - $targetName = $group.displayName - } - else { - $targetName = $targetGroupId - Write-Verbose "Could not retrieve group name for Group ID: $targetGroupId" - } - } - catch { - $targetName = $targetGroupId - Write-Verbose "Failed to retrieve group name for Group ID: $targetGroupId - $($_.Exception.Message)" - } - } - - # Create policy assignment object - $policyAssignment = [PSCustomObject]@{ - PolicyType = "Compliance" - PolicyId = $policy.id - PolicyName = $policy.displayName - PolicyDescription = $policy.description - AssignmentId = $assignment.id - TargetType = $assignment.target.'@odata.type' - TargetId = $targetGroupId - TargetName = $targetName - Intent = $assignment.intent - Source = $assignment.source - } - - $policyAssignments += $policyAssignment - } - } - catch { - # If API call failed, create entry with error information - Write-Verbose "Failed to retrieve assignments for compliance policy '$($policy.displayName)': $($_.Exception.Message)" - $policyAssignment = [PSCustomObject]@{ - PolicyType = "Compliance" - PolicyId = $policy.id - PolicyName = $policy.displayName - PolicyDescription = $policy.description - AssignmentId = $null - TargetType = "Error" - TargetId = $null - TargetName = "Error retrieving assignments: $($_.Exception.Message)" - Intent = $null - Source = $null - } - - $policyAssignments += $policyAssignment - } + + $url = "https://graph.microsoft.com/v1.0/deviceManagement/deviceCompliancePolicies('$($policy.id)')/assignments" + $policyAssignments += @(Get-PolicyAssignmentRow -Type "Compliance" -Policy $policy -AssignmentsUrl $url) } Write-Progress -Activity "Processing compliance policies" -Completed } - + # Display results Write-Host "`nPolicy Assignments:" -ForegroundColor Cyan Write-Host "===================" -ForegroundColor Cyan - + if ($policyAssignments.Count -eq 0) { - Write-Host "No policy assignments found." -ForegroundColor Yellow + Write-Host "No policies found." -ForegroundColor Yellow } else { - # Group results by policy type for better display - $configAssignments = $policyAssignments | Where-Object { $_.PolicyType -eq "Configuration" } - $complianceAssignments = $policyAssignments | Where-Object { $_.PolicyType -eq "Compliance" } - - if ($configAssignments.Count -gt 0) { - Write-Host "`nConfiguration Profiles: $($configAssignments.Count) assignment(s)" -ForegroundColor Green - foreach ($assignment in $configAssignments) { - Write-Host " Policy: $($assignment.PolicyName)" -ForegroundColor White - Write-Host " Target: $($assignment.TargetName) ($($assignment.TargetType))" -ForegroundColor Gray - Write-Host " Intent: $($assignment.Intent)" -ForegroundColor Gray - } - } - - if ($complianceAssignments.Count -gt 0) { - Write-Host "`nCompliance Policies: $($complianceAssignments.Count) assignment(s)" -ForegroundColor Green - foreach ($assignment in $complianceAssignments) { - Write-Host " Policy: $($assignment.PolicyName)" -ForegroundColor White - Write-Host " Target: $($assignment.TargetName) ($($assignment.TargetType))" -ForegroundColor Gray - Write-Host " Intent: $($assignment.Intent)" -ForegroundColor Gray + foreach ($type in @("Configuration", "Compliance")) { + $rows = @($policyAssignments | Where-Object { $_.PolicyType -eq $type }) + if ($rows.Count -eq 0) { continue } + + $assigned = @($rows | Where-Object { $_.TargetType -notin @("None", "Error") }) + $unassigned = @($rows | Where-Object { $_.TargetType -eq "None" }) + $failed = @($rows | Where-Object { $_.TargetType -eq "Error" }) + + Write-Host "${type}: $($assigned.Count) assignment(s), $($unassigned.Count) policy(ies) with no assignment, $($failed.Count) policy(ies) with an error" -ForegroundColor Green + foreach ($row in $assigned) { + Write-Host " Policy: $($row.PolicyName)" -ForegroundColor White + Write-Host " Target: $($row.TargetName) ($($row.TargetType))" -ForegroundColor Gray + Write-Host " Intent: $($row.Intent)" -ForegroundColor Gray } + foreach ($row in $unassigned) { Write-Host " Not assigned: $($row.PolicyName)" -ForegroundColor Yellow } + foreach ($row in $failed) { Write-Host " Error: $($row.PolicyName) - $($row.TargetName)" -ForegroundColor Red } } - + # Export to CSV if path is specified if ($ExportPath) { - # Create directory if it doesn't exist $exportDirectory = Split-Path -Path $ExportPath -Parent if ($exportDirectory -and -not (Test-Path -Path $exportDirectory)) { New-Item -Path $exportDirectory -ItemType Directory -Force | Out-Null } - - # Export results to CSV file - $policyAssignments | Export-Csv -Path $ExportPath -NoTypeInformation -Encoding UTF8 + + $policyAssignments | ConvertTo-SafeCsvRecord | Export-Csv -Path $ExportPath -NoTypeInformation -Encoding UTF8 Write-Host "`nResults exported to: $ExportPath" -ForegroundColor Green - - # Verify the export file was created successfully + if (-not (Test-Path -Path $ExportPath)) { Write-Error "Export file was not created successfully at: $ExportPath" exit 1 } } } - - Write-Host "`nQuery completed successfully. Found $($policyAssignments.Count) policy assignment(s)." -ForegroundColor Green + + if ($script:assignmentErrorCount -gt 0) { + Write-Error "The report is incomplete: assignments could not be retrieved for $($script:assignmentErrorCount) policy(ies). They are marked TargetType 'Error'." + exit 1 + } + + Write-Host "`nQuery completed successfully. Found $($policyAssignments.Count) policy assignment row(s)." -ForegroundColor Green } # Error handling block - catches exceptions during Graph API calls catch { - # Capture and display the error message with script name for context $errMsg = $_.Exception.Message Write-Error "Get-IntunePolicyAssignments: Failed to retrieve policy assignments - $errMsg" - - # Provide additional error context if available + if ($_.Exception.Response) { $statusCode = $_.Exception.Response.StatusCode.value__ Write-Verbose "HTTP Status Code: $statusCode" } - + if ($_.Exception.InnerException) { Write-Verbose "Inner Exception: $($_.Exception.InnerException.Message)" } - + if ($PSBoundParameters.ContainsKey('Verbose')) { Write-Verbose "Stack Trace: $($_.ScriptStackTrace)" } - + exit 1 } - diff --git a/Reporting/Get-IntuneWin32AppDetails.ps1 b/Reporting/Get-IntuneWin32AppDetails.ps1 index 80ea09c..4b2a7ef 100644 --- a/Reporting/Get-IntuneWin32AppDetails.ps1 +++ b/Reporting/Get-IntuneWin32AppDetails.ps1 @@ -4,8 +4,20 @@ .DESCRIPTION This script connects to Microsoft Graph API and retrieves detailed information about - Win32 app deployments in Intune including app installation status, deployment progress, - installation errors, and app assignment details. It can query a specific app or all apps. + Win32 app deployments in Intune: the app, its install and uninstall commands, and its + assignments. It can query a specific app or all apps. Every query is read through all result pages. + + When -DeviceId is given, each app also gets the install state Intune reports for that device + (beta endpoint mobileApps/{id}/deviceStatuses, matched on the device ID). The states are Graph's own: + installed, failed, notInstalled, uninstallFailed, pendingInstall, unknown, notApplicable. + "NotReported" means Intune has no status row for that app on that device, which is the case for + an app that is not targeted at it. Installed software inventory (detectedApps) is not used, + because its display names rarely equal the Intune app name. + This is one extra request (more for large result sets) per app. + + If an app's assignments or its device status cannot be read (for example a missing permission or + a 429 after retries), the app gets an AssignmentError or DeviceStatusError value instead of an + empty result, the report says it is incomplete and the script exits 1. .PARAMETER AppId The Application (Client) ID of your Entra ID registered app. Can also be provided via @@ -15,385 +27,275 @@ Your Azure AD Tenant ID. Can also be provided via INTUNE_TENANT_ID environment variable. .PARAMETER ClientSecret - The Client Secret of your Entra ID registered app. Can also be provided via + The Client Secret of your Entra ID registered app, as plain text. A secret on the command line + ends up in shell history and process listings; prefer -ClientSecretSecure or the INTUNE_CLIENT_SECRET environment variable. +.PARAMETER ClientSecretSecure + The Client Secret as a SecureString, for example from Read-Host -AsSecureString or a vault. + .PARAMETER IntuneAppId Optional. The Intune app ID to query. If not specified, retrieves all Win32 apps. .PARAMETER DeviceId Optional. The device ID to query app installation status for. If specified, shows - app installation status for that device. + the reported install state of each app on that device. .PARAMETER ExportPath Optional. Path to export results to CSV file. If not specified, results are displayed only. .EXAMPLE - .\Get-IntuneWin32AppDetails.ps1 -AppId 'your-app-id' -TenantId 'your-tenant-id' -ClientSecret 'your-secret' + .\Get-IntuneWin32AppDetails.ps1 -AppId 'your-app-id' -TenantId 'your-tenant-id' -ClientSecretSecure (Read-Host -AsSecureString 'Client secret') .EXAMPLE .\Get-IntuneWin32AppDetails.ps1 -IntuneAppId 'app-guid' -DeviceId 'device-guid' -ExportPath 'C:\Temp\AppDetails.csv' .NOTES - Requires: Microsoft.Graph PowerShell module - Requires: Entra ID App Registration with DeviceManagementApps.Read.All and DeviceManagementManagedDevices.Read.All permissions + Requires: Entra ID App Registration with the DeviceManagementApps.Read.All APPLICATION permission + (admin consent granted). + Exit Codes: + - 0: Report complete + - 1: A failure, or at least one app's assignments or device status could not be retrieved #> [CmdletBinding()] # Define script parameters for credential input and query options -# These allow credentials and query parameters to be passed as command-line arguments param( [Parameter(Mandatory=$false)] [string]$AppId, - + [Parameter(Mandatory=$false)] [string]$TenantId, - + [Parameter(Mandatory=$false)] [string]$ClientSecret, - + + [Parameter(Mandatory=$false)] + [securestring]$ClientSecretSecure, + [Parameter(Mandatory=$false)] [string]$IntuneAppId, - + [Parameter(Mandatory=$false)] [string]$DeviceId, - + [Parameter(Mandatory=$false)] [string]$ExportPath ) -# Check if Microsoft.Graph module is installed, and install if missing -# This module is required to interact with Microsoft Graph API -if(-not (Get-Module -Name Microsoft.Graph -ListAvailable)) -{ - try { - # Try to install for current user first (doesn't require admin privileges) - # This is the preferred method as it doesn't require elevation - Install-Module -Name Microsoft.Graph -Repository PSGallery -Scope CurrentUser -Force -AllowClobber -SkipPublisherCheck -ErrorAction Stop - Write-Host "Microsoft.Graph module installed successfully for current user." -ForegroundColor Green - } - catch [Exception] { - # If user-scope installation fails, try system-wide installation - # This requires administrator privileges - Write-Warning "Failed to install module for current user: $($_.Exception.Message)" - Write-Host "Attempting system-wide installation (requires admin privileges)..." -ForegroundColor Yellow - try { - Install-Module -Name Microsoft.Graph -Repository PSGallery -Force -AllowClobber -SkipPublisherCheck -ErrorAction Stop - Write-Host "Microsoft.Graph module installed successfully system-wide." -ForegroundColor Green - } - catch { - # If both installation methods fail, exit with error - Write-Error "Failed to install Microsoft.Graph module: $($_.Exception.Message)" - exit 1 - } - } +# Shared Graph helpers: token request, retry, paging, CSV safety +try { + Import-Module (Join-Path $PSScriptRoot '..\Common\IntuneCommon.psd1') -ErrorAction Stop } - -# Import the Microsoft Graph PowerShell module into the current session -# This makes the Graph API cmdlets available for use -try{ - Import-Module -Name Microsoft.Graph -}catch [Exception] { - # Display error message if import fails - Write-Error "Failed to import Microsoft.Graph module: $($_.Exception.Message)" +catch { + Write-Error "Failed to import the IntuneCommon module: $($_.Exception.Message)" exit 1 } -# Credential handling: Check parameters first, then environment variables -# This provides flexibility in how credentials are provided -$appid = if ($AppId) { $AppId } elseif ($env:INTUNE_APP_ID) { $env:INTUNE_APP_ID } else { '' } -$tenantid = if ($TenantId) { $TenantId } elseif ($env:INTUNE_TENANT_ID) { $env:INTUNE_TENANT_ID } else { '' } -$clientsecret = if ($ClientSecret) { $ClientSecret } elseif ($env:INTUNE_CLIENT_SECRET) { $env:INTUNE_CLIENT_SECRET } else { '' } - -# Validate that credentials are not placeholder values -# This prevents accidental use of placeholder credentials -if ($appid -match '^<.*>$' -or $tenantid -match '^<.*>$' -or $clientsecret -match '^<.*>$') { - Write-Error "Please provide valid credentials via parameters or environment variables (INTUNE_APP_ID, INTUNE_TENANT_ID, INTUNE_CLIENT_SECRET)." +# Credential handling: parameters first, then environment variables. Placeholders are rejected. +try { + $credential = Get-IntuneCredential -AppId $AppId -TenantId $TenantId -ClientSecret $ClientSecret -ClientSecretSecure $ClientSecretSecure +} +catch { + Write-Error $_.Exception.Message exit 1 } -# Validate DeviceId format if provided -if ($DeviceId -and -not ($DeviceId -match '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$')) { +# Validate DeviceId and IntuneAppId format if provided +if ($DeviceId -and -not (Test-GuidFormat -Guid $DeviceId)) { Write-Error "DeviceId must be a valid GUID format." exit 1 } - -# Validate IntuneAppId format if provided -if ($IntuneAppId -and -not ($IntuneAppId -match '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$')) { +if ($IntuneAppId -and -not (Test-GuidFormat -Guid $IntuneAppId)) { Write-Error "IntuneAppId must be a valid GUID format." exit 1 } +# Build the report row for one Win32 app, reading its assignments. +# A failure is recorded on the row (AssignmentError) and counted; it is never turned into "0 assignments". +function Get-AppDetailRow { + param([Parameter(Mandatory=$true)] $App) + + $assignmentCount = $null + $assignmentText = $null + $assignmentError = $null + + try { + $url = "https://graph.microsoft.com/v1.0/deviceAppManagement/mobileApps('$($App.id)')/assignments" + $assignments = @(Get-GraphApiAllPages -Uri $url -Headers $script:headers) + $assignmentCount = $assignments.Count + $assignmentText = ($assignments | ForEach-Object { $_.target.'@odata.type' }) -join '; ' + } + catch { + $assignmentError = "Could not read assignments: $($_.Exception.Message)" + $script:errorCount++ + Write-Verbose "$assignmentError (app $($App.id))" + } + + [PSCustomObject][ordered]@{ + AppId = $App.id + AppName = $App.displayName + AppDescription = $App.description + AppVersion = if ($App.displayVersion) { $App.displayVersion } else { $App.version } + AppType = "Win32" + Publisher = $App.publisher + InstallCommandLine = $App.installCommandLine + UninstallCommandLine = $App.uninstallCommandLine + MinimumSupportedOperatingSystem = $App.minimumSupportedOperatingSystem + AssignmentCount = $assignmentCount + Assignments = $assignmentText + AssignmentError = $assignmentError + } +} + +# Add the install state Intune reports for one device to a report row. +function Add-DeviceInstallState { + param( + [Parameter(Mandatory=$true)] $Row, + [Parameter(Mandatory=$true)] [string]$ManagedDeviceId + ) + + $state = "NotReported" + $version = $null + $deviceError = $null + + try { + # deviceStatuses is documented in the Graph beta endpoint only, so this one call uses beta. The rest of the script uses v1.0. + $url = "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps('$($Row.AppId)')/deviceStatuses" + $statuses = @(Get-GraphApiAllPages -Uri $url -Headers $script:headers) + $mine = $statuses | Where-Object { $_.deviceId -eq $ManagedDeviceId } | Select-Object -First 1 + if ($mine) { + $state = if ($mine.installState) { $mine.installState } else { "unknown" } + $version = $mine.displayVersion + } + } + catch { + $state = "Unknown" + $deviceError = "Could not read device status: $($_.Exception.Message)" + $script:errorCount++ + Write-Verbose "$deviceError (app $($Row.AppId))" + } + + $Row | Add-Member -MemberType NoteProperty -Name "DeviceInstallStatus" -Value $state -Force + $Row | Add-Member -MemberType NoteProperty -Name "DeviceInstallVersion" -Value $version -Force + $Row | Add-Member -MemberType NoteProperty -Name "DeviceStatusError" -Value $deviceError -Force +} + # Main script execution wrapped in try-catch for error handling try { - # Import shared module for Graph API utilities - Import-Module "$PSScriptRoot\..\Common\IntuneCommon.psm1" -Force -ErrorAction Stop - - # Connect to Microsoft Graph API using app registration credentials - # This authenticates the script to access Intune data via Graph API Write-Host "Connecting to Microsoft Graph API..." -ForegroundColor Yellow - - $body = @{ - grant_type = "client_credentials" - scope = "https://graph.microsoft.com/.default" - client_id = $appid - client_secret = $clientsecret - } - - # Request an access token from Microsoft identity platform - # The token is used to authenticate subsequent Graph API requests - $tokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenantid/oauth2/v2.0/token" -Method Post -Body $body - $accessToken = $tokenResponse.access_token - - # Set up headers for Graph API requests - # The access token is included in the Authorization header - $headers = @{ - "Authorization" = "Bearer $accessToken" - "Content-Type" = "application/json" - } - + $script:headers = Get-IntuneGraphHeaders -AppRegistration $credential Write-Host "Successfully connected to Microsoft Graph API." -ForegroundColor Green - - # Initialize array to store app details - # This will hold all app information retrieved from Graph API + + $script:errorCount = 0 $appDetails = @() - - # Determine which apps to query - # If IntuneAppId is specified, query only that app - # Otherwise, query all Win32 apps + if ($IntuneAppId) { Write-Host "Querying details for app: $IntuneAppId" -ForegroundColor Yellow - - # Query app details for specific app - # Get comprehensive app information - $appUrl = "https://graph.microsoft.com/v1.0/deviceAppManagement/mobileApps('$IntuneAppId')" - try { - $app = Invoke-GraphApiWithRetry -Uri $appUrl -Headers $headers -Method Get - - if ($null -eq $app) { - Write-Error "App not found or API returned null response for app ID: $IntuneAppId" - exit 1 - } - - # Check if this is a Win32 app - # Win32 apps have a specific OData type - if ($app.'@odata.type' -eq '#microsoft.graph.win32LobApp') { - # Get app assignments - # Get all assignments for this app - $assignmentsUrl = "https://graph.microsoft.com/v1.0/deviceAppManagement/mobileApps('$IntuneAppId')/assignments" - try { - $assignments = Invoke-GraphApiWithRetry -Uri $assignmentsUrl -Headers $headers -Method Get - if ($null -eq $assignments -or $null -eq $assignments.value) { - $assignments = @{ value = @() } - } - } - catch { - $assignments = @{ value = @() } - Write-Verbose "Could not retrieve assignments for app: $($_.Exception.Message)" - } - - # Create app detail object - $appDetail = [PSCustomObject]@{ - AppId = $app.id - AppName = $app.displayName - AppDescription = $app.description - AppVersion = $app.version - AppType = "Win32" - Publisher = $app.publisher - InstallCommandLine = $app.installCommandLine - UninstallCommandLine = $app.uninstallCommandLine - MinimumSupportedOperatingSystem = $app.minimumSupportedOperatingSystem - AssignmentCount = $assignments.value.Count - Assignments = ($assignments.value | ForEach-Object { $_.target.'@odata.type' }) -join '; ' - } - - $appDetails += $appDetail - } - else { - Write-Warning "App $IntuneAppId is not a Win32 app. Type: $($app.'@odata.type')" - } + + # A failed fetch is a failure of the whole run (caught below, exit 1), not a "completed successfully" + $app = Invoke-GraphApiWithRetry -Uri "https://graph.microsoft.com/v1.0/deviceAppManagement/mobileApps('$IntuneAppId')" -Headers $script:headers -Method Get + if ($null -eq $app) { + Write-Error "App not found or API returned null response for app ID: $IntuneAppId" + exit 1 } - catch { - Write-Error "Failed to retrieve app details: $($_.Exception.Message)" + + if ($app.'@odata.type' -eq '#microsoft.graph.win32LobApp') { + $appDetails += Get-AppDetailRow -App $app + } + else { + Write-Warning "App $IntuneAppId is not a Win32 app. Type: $($app.'@odata.type')" } } else { Write-Host "Querying details for all Win32 apps..." -ForegroundColor Yellow - - # Query all Win32 apps from Intune - $appsUrl = "https://graph.microsoft.com/v1.0/deviceAppManagement/mobileApps?`$filter=isof('microsoft.graph.win32LobApp')" - $apps = Invoke-GraphApiWithRetry -Uri $appsUrl -Headers $headers -Method Get - - # Handle null response and pagination - $allApps = @() - if ($null -ne $apps -and $null -ne $apps.value) { - $allApps += $apps.value - } - $pageCount = 1 - while ($null -ne $apps -and $null -ne $apps.'@odata.nextLink') { - $pageCount++ - Write-Progress -Activity "Retrieving Win32 apps" -Status "Fetching page $pageCount" -PercentComplete -1 - $apps = Invoke-GraphApiWithRetry -Uri $apps.'@odata.nextLink' -Headers $headers -Method Get - if ($null -ne $apps -and $null -ne $apps.value) { - $allApps += $apps.value - } - } - Write-Progress -Activity "Retrieving Win32 apps" -Completed - + + $appsUrl = "https://graph.microsoft.com/v1.0/deviceAppManagement/mobileApps?`$filter=$([uri]::EscapeDataString("isof('microsoft.graph.win32LobApp')"))" + $allApps = @(Get-GraphApiAllPages -Uri $appsUrl -Headers $script:headers) Write-Host "Found $($allApps.Count) Win32 app(s). Processing..." -ForegroundColor Cyan - - # Process each app and get its details + $appCount = 0 foreach ($app in $allApps) { $appCount++ Write-Progress -Activity "Processing Win32 apps" -Status "Processing app $appCount of $($allApps.Count): $($app.displayName)" -PercentComplete (($appCount / $allApps.Count) * 100) Write-Host "Processing app $appCount of $($allApps.Count): $($app.displayName)" -ForegroundColor Cyan - - # Get app assignments - # Get all assignments for this app - $assignmentsUrl = "https://graph.microsoft.com/v1.0/deviceAppManagement/mobileApps('$($app.id)')/assignments" - try { - $assignments = Invoke-GraphApiWithRetry -Uri $assignmentsUrl -Headers $headers -Method Get - if ($null -eq $assignments -or $null -eq $assignments.value) { - $assignments = @{ value = @() } - } - } - catch { - $assignments = @{ value = @() } - Write-Verbose "Could not retrieve assignments for app: $($_.Exception.Message)" - } - - # Create app detail object - $appDetail = [PSCustomObject]@{ - AppId = $app.id - AppName = $app.displayName - AppDescription = $app.description - AppVersion = $app.version - AppType = "Win32" - Publisher = $app.publisher - InstallCommandLine = $app.installCommandLine - UninstallCommandLine = $app.uninstallCommandLine - MinimumSupportedOperatingSystem = $app.minimumSupportedOperatingSystem - AssignmentCount = $assignments.value.Count - Assignments = ($assignments.value | ForEach-Object { $_.target.'@odata.type' }) -join '; ' - } - - $appDetails += $appDetail + $appDetails += Get-AppDetailRow -App $app } Write-Progress -Activity "Processing Win32 apps" -Completed } - - # If DeviceId is specified, get app installation status for that device + + # If DeviceId is specified, add the reported install state of each app on that device if ($DeviceId) { Write-Host "`nQuerying app installation status for device: $DeviceId" -ForegroundColor Yellow - - # Query device app installation status - $deviceAppsUrl = "https://graph.microsoft.com/v1.0/deviceManagement/managedDevices('$DeviceId')/detectedApps" - try { - $deviceApps = Invoke-GraphApiWithRetry -Uri $deviceAppsUrl -Headers $headers -Method Get - - # Handle null or empty response - if ($null -ne $deviceApps -and $null -ne $deviceApps.value) { - Write-Host "Found $($deviceApps.value.Count) app(s) detected on device." -ForegroundColor Cyan - - # Match detected apps with Win32 apps - foreach ($appDetail in $appDetails) { - $detectedApp = $deviceApps.value | Where-Object { $_.displayName -eq $appDetail.AppName } - if ($detectedApp) { - $appDetail | Add-Member -MemberType NoteProperty -Name "DeviceInstallStatus" -Value "Installed" -Force - $appDetail | Add-Member -MemberType NoteProperty -Name "DeviceInstallVersion" -Value $detectedApp.version -Force - } - else { - $appDetail | Add-Member -MemberType NoteProperty -Name "DeviceInstallStatus" -Value "Not Installed" -Force - $appDetail | Add-Member -MemberType NoteProperty -Name "DeviceInstallVersion" -Value $null -Force - } - } - } - else { - Write-Warning "No apps detected on device or API returned null response" - foreach ($appDetail in $appDetails) { - $appDetail | Add-Member -MemberType NoteProperty -Name "DeviceInstallStatus" -Value "Unknown" -Force - $appDetail | Add-Member -MemberType NoteProperty -Name "DeviceInstallVersion" -Value $null -Force - } - } - } - catch { - Write-Warning "Could not retrieve app installation status for device: $($_.Exception.Message)" - foreach ($appDetail in $appDetails) { - $appDetail | Add-Member -MemberType NoteProperty -Name "DeviceInstallStatus" -Value "Unknown" -Force - $appDetail | Add-Member -MemberType NoteProperty -Name "DeviceInstallVersion" -Value $null -Force - } - } + foreach ($row in $appDetails) { Add-DeviceInstallState -Row $row -ManagedDeviceId $DeviceId } } - + # Display results Write-Host "`nWin32 App Details:" -ForegroundColor Cyan Write-Host "==================" -ForegroundColor Cyan - + if ($appDetails.Count -eq 0) { Write-Host "No Win32 apps found matching the specified criteria." -ForegroundColor Yellow } else { - # Display each app's details foreach ($detail in $appDetails) { Write-Host "`nApp: $($detail.AppName)" -ForegroundColor Green Write-Host " App ID: $($detail.AppId)" -ForegroundColor White Write-Host " Publisher: $($detail.Publisher)" -ForegroundColor White Write-Host " Version: $($detail.AppVersion)" -ForegroundColor White Write-Host " Install Command: $($detail.InstallCommandLine)" -ForegroundColor White - Write-Host " Assignment Count: $($detail.AssignmentCount)" -ForegroundColor White + if ($detail.AssignmentError) { Write-Host " ERROR: $($detail.AssignmentError)" -ForegroundColor Red } + else { Write-Host " Assignment Count: $($detail.AssignmentCount)" -ForegroundColor White } if ($detail.DeviceInstallStatus) { - Write-Host " Device Install Status: $($detail.DeviceInstallStatus)" -ForegroundColor $(if ($detail.DeviceInstallStatus -eq 'Installed') { 'Green' } else { 'Yellow' }) - if ($detail.DeviceInstallVersion) { - Write-Host " Device Install Version: $($detail.DeviceInstallVersion)" -ForegroundColor White - } + Write-Host " Device Install Status: $($detail.DeviceInstallStatus)" -ForegroundColor $(if ($detail.DeviceInstallStatus -eq 'installed') { 'Green' } else { 'Yellow' }) + if ($detail.DeviceInstallVersion) { Write-Host " Device Install Version: $($detail.DeviceInstallVersion)" -ForegroundColor White } + if ($detail.DeviceStatusError) { Write-Host " ERROR: $($detail.DeviceStatusError)" -ForegroundColor Red } } } - + # Export to CSV if path is specified if ($ExportPath) { - # Create directory if it doesn't exist $exportDirectory = Split-Path -Path $ExportPath -Parent if ($exportDirectory -and -not (Test-Path -Path $exportDirectory)) { New-Item -Path $exportDirectory -ItemType Directory -Force | Out-Null } - - # Export results to CSV file - $appDetails | Export-Csv -Path $ExportPath -NoTypeInformation -Encoding UTF8 + + $appDetails | ConvertTo-SafeCsvRecord | Export-Csv -Path $ExportPath -NoTypeInformation -Encoding UTF8 Write-Host "`nResults exported to: $ExportPath" -ForegroundColor Green - - # Verify the export file was created successfully + if (-not (Test-Path -Path $ExportPath)) { Write-Error "Export file was not created successfully at: $ExportPath" exit 1 } } } - + + if ($script:errorCount -gt 0) { + Write-Error "The report is incomplete: $($script:errorCount) request(s) failed. Affected rows have an AssignmentError or DeviceStatusError value." + exit 1 + } + Write-Host "`nQuery completed successfully. Found $($appDetails.Count) Win32 app(s)." -ForegroundColor Green } # Error handling block - catches exceptions during Graph API calls catch { - # Capture and display the error message with script name for context $errMsg = $_.Exception.Message Write-Error "Get-IntuneWin32AppDetails: Failed to retrieve Win32 app details - $errMsg" - - # Provide additional error context if available + if ($_.Exception.Response) { $statusCode = $_.Exception.Response.StatusCode.value__ Write-Verbose "HTTP Status Code: $statusCode" } - + if ($_.Exception.InnerException) { Write-Verbose "Inner Exception: $($_.Exception.InnerException.Message)" } - + if ($PSBoundParameters.ContainsKey('Verbose')) { Write-Verbose "Stack Trace: $($_.ScriptStackTrace)" } - + exit 1 } - diff --git a/Security/Disable-PrintSpoolerService.ps1 b/Security/Disable-PrintSpoolerService.ps1 index 985bc60..e7ca8a9 100644 --- a/Security/Disable-PrintSpoolerService.ps1 +++ b/Security/Disable-PrintSpoolerService.ps1 @@ -1,4 +1,4 @@ -#Requires -RunAsAdministrator +#Requires -RunAsAdministrator <# .SYNOPSIS @@ -42,8 +42,14 @@ try { if ($service.Status -eq "Running") { if ($PSCmdlet.ShouldProcess("Print Spooler service", "Stop service")) { + # No -Force: -Force would also stop every running dependent service. If a dependent is + # running, Stop-Service fails with a message naming it and the script exits 1. + $runningDependents = @($service.DependentServices | Where-Object { $_.Status -eq 'Running' }) + if ($runningDependents.Count -gt 0) { + Write-Warning "Running services that depend on the Print Spooler: $(($runningDependents | ForEach-Object { $_.Name }) -join ', ')" + } Write-Host "Stopping Print Spooler service..." -ForegroundColor Yellow - Stop-Service -Name "Spooler" -Force -ErrorAction Stop + Stop-Service -Name "Spooler" -ErrorAction Stop Write-Host "Print Spooler service stopped successfully." -ForegroundColor Green } } diff --git a/Security/Disable-SmartCardLogonEnforcement.ps1 b/Security/Disable-SmartCardLogonEnforcement.ps1 index 61ac0bc..6765e0c 100644 --- a/Security/Disable-SmartCardLogonEnforcement.ps1 +++ b/Security/Disable-SmartCardLogonEnforcement.ps1 @@ -10,9 +10,15 @@ and disables automatic lock on smart card removal. The script also disables the Smart Card Policy Service. + This is also the way back from Enable-SmartCardLogonEnforcement.ps1 on a device that can + still check in to Intune. + + Every registry write uses -ErrorAction Stop and is read back after it is written. If any write + or read-back fails the script exits 1. The log file is always kept. + .PARAMETER KeepLogs - Keeps the log file after script execution instead of removing it. - Useful for troubleshooting purposes. + Retained so existing callers keep working. It has no effect: the log file is always kept now, + because this script changes a security setting and should leave an audit trail. .EXAMPLE .\Disable-SmartCardLogonEnforcement.ps1 @@ -20,12 +26,13 @@ .EXAMPLE .\Disable-SmartCardLogonEnforcement.ps1 -WhatIf -.EXAMPLE - .\Disable-SmartCardLogonEnforcement.ps1 -KeepLogs - .NOTES Requires: Administrator privileges - Modifies: HKLM registry keys + Modifies: HKLM registry keys, SCPolicySvc startup type + Log: %ProgramData%\Microsoft\IntuneManagementExtension\Logs\win32-Disable_SmartCardLogon_Enforcement.log + Exit Codes: + - 0: All changes applied and verified, or a -WhatIf run + - 1: A change failed or verification failed #> [CmdletBinding(SupportsShouldProcess=$true)] @@ -34,191 +41,177 @@ param( [switch]$KeepLogs ) -# Architecture check: If running as a 32-bit process on an x64 system, re-launch as a 64-bit process -# This ensures registry modifications are made to the correct registry hive (64-bit vs 32-bit) -# PROCESSOR_ARCHITEW6432 is set on 64-bit systems when running 32-bit processes +# Build the argument list used to relaunch this script in 64-bit PowerShell. +# Every switch that was passed (-WhatIf, -Verbose, -KeepLogs) is forwarded, so the child +# does what the caller asked. Dropping -WhatIf here would make the 64-bit child change the machine. +function Get-RelaunchArgumentList { + [CmdletBinding()] + param( + [Parameter(Mandatory=$true)] + [string]$ScriptPath, + + [Parameter(Mandatory=$false)] + [hashtable]$BoundParameters = @{} + ) + + $arguments = @('-ExecutionPolicy', 'Bypass', '-NoProfile', '-File', $ScriptPath) + foreach ($key in $BoundParameters.Keys) { + $value = $BoundParameters[$key] + if ($value -is [System.Management.Automation.SwitchParameter]) { + if ($value.IsPresent) { $arguments += "-$key" } + } + } + return $arguments +} + +# Architecture check: if running as a 32-bit process on a 64-bit system, relaunch as 64-bit +# so registry writes go to the 64-bit hive. PROCESSOR_ARCHITEW6432 is set for 32-bit processes on 64-bit Windows. if ($env:PROCESSOR_ARCHITEW6432 -and $env:PROCESSOR_ARCHITEW6432 -ne "ARM64") { - # Check if the 64-bit PowerShell executable exists in the SysNative path - # SysNative is a special path that allows 32-bit processes to access 64-bit system files - if (Test-Path "$($env:WINDIR)\SysNative\WindowsPowerShell\v1.0\powershell.exe") + # SysNative lets a 32-bit process reach the 64-bit system files + $sysNativePowerShell = "$($env:WINDIR)\SysNative\WindowsPowerShell\v1.0\powershell.exe" + if (Test-Path $sysNativePowerShell) { - # Re-launch the script in 64-bit PowerShell - # -ExecutionPolicy bypass: Allows script execution regardless of execution policy - # -NoProfile: Starts PowerShell without loading user profile (faster startup) - # -File: Specifies the script file to execute - & "$($env:WINDIR)\SysNative\WindowsPowerShell\v1.0\powershell.exe" -ExecutionPolicy bypass -NoProfile -File "$PSCommandPath" - # Exit with the same exit code as the re-launched script + $relaunchArguments = Get-RelaunchArgumentList -ScriptPath $PSCommandPath -BoundParameters $PSBoundParameters + & $sysNativePowerShell @relaunchArguments exit $LASTEXITCODE } } - -# Logging Preparation Section -# Set up variables for logging script execution to a log file -# Define the application name for log file naming +# Logging Preparation Section $AppName = "Disable_SmartCardLogon_Enforcement" - -# Construct the log file name using Intune naming convention $Log_FileName = "win32-$AppName.log" - -# Define the log file path (Intune Management Extension logs directory) -# Use environment variable for cross-system compatibility $Log_Path = Join-Path $env:ProgramData "Microsoft\IntuneManagementExtension\Logs" +$TestPath = Join-Path $Log_Path $Log_FileName +$SectionLine = "* * " * 10 -# Construct the full path to the log file -$TestPath = "$Log_Path\$Log_FileName" - -# Define a section line separator for log readability (asterisks repeated 10 times) -$SectionLine="* * "*10 - -# Check if the log file exists, create it if it doesn't -# This ensures logging can proceed even if the file doesn't exist -If(!(Test-Path $TestPath)) -{ - # Create the log file in the Intune logs directory - New-Item -Path $Log_Path -Name $Log_FileName -ItemType "File" -Force -} - -# Define a logging function to write timestamped messages to the log file -function Write-Log { +# Write a timestamped message to the log file and to the console. +# Under -WhatIf nothing is written to disk, so a dry run leaves no files behind. +function Write-ScriptLog { [CmdletBinding()] param( [Parameter()] - [string]$Message # The message to write to the log + [string]$Message ) - # Get current date and time formatted as "DayOfWeek MM/dd/yyyy HH:mm:ss" $timestamp = Get-Date -Format "dddd MM/dd/yyyy HH:mm:ss" - # Append the timestamped message to the log file - Add-Content -Path $TestPath -Value "$timestamp : $Message" + if ($WhatIfPreference) { + Write-Host "[log] $Message" + return + } + try { + if (-not (Test-Path -Path $Log_Path)) { + New-Item -Path $Log_Path -ItemType Directory -Force -ErrorAction Stop | Out-Null + } + Add-Content -Path $TestPath -Value "$timestamp : $Message" -ErrorAction Stop + } + catch { + Write-Warning "Could not write to log file ${TestPath}: $($_.Exception.Message)" + } } -# Start logging - write initial log entries -# This log file can also be used by Intune Management Extension for detection -Write-Log "Begin..." -Write-Log $SectionLine +# Set one DWORD registry value and read it back. Throws if the write or the read-back fails. +# Creates the key only when it is missing, and only when the change is confirmed (-WhatIf creates nothing). +function Set-RegistryDwordVerified { + [CmdletBinding(SupportsShouldProcess=$true)] + param( + [Parameter(Mandatory=$true)] + [string]$Path, + + [Parameter(Mandatory=$true)] + [string]$Name, -# Section 1: Disable Smart Card Logon Enforcement -# This section modifies the registry to allow password-based logon instead of requiring smart cards + [Parameter(Mandatory=$true)] + [int]$Value, -try -{ - # Check if the System policies registry path exists - # This path contains policy settings including smart card enforcement - if (-NOT (Test-Path -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System')) { - # Registry path doesn't exist - create it - Write-Log "Reg path not found, hence creating Reg path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" - New-Item -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' -Force -ErrorAction SilentlyContinue | Out-Null + [Parameter(Mandatory=$true)] + [string]$Description + ) + + if (-not $PSCmdlet.ShouldProcess("$Path\$Name", $Description)) { + return } - - # Set the scforceoption registry value to 0 - # Value 0 = Allow password logon (smart card not required) - # Value 1 = Require smart card for interactive logon - if ($PSCmdlet.ShouldProcess('HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\scforceoption', 'Set value to 0 (allow password logon)')) { - Write-Log "Reg path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System found, resetting Reg key scforceoption with value 0" - New-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' -Name 'scforceoption' -Value 0 -Force -ErrorAction SilentlyContinue | Out-Null - Write-Log "Reg key value resetted to default" + + if (-not (Test-Path -LiteralPath $Path)) { + Write-ScriptLog "Reg path $Path not found, creating it" + New-Item -Path $Path -Force -ErrorAction Stop | Out-Null } -} -catch -{ - # Log any errors that occur during registry modification with enhanced details - $errMsg = $_.Exception.Message - Write-Log "Error: $errMsg" - if ($_.Exception.InnerException) { - Write-Log "Inner Exception: $($_.Exception.InnerException.Message)" + + Write-ScriptLog "Setting $Path\$Name to $Value" + New-ItemProperty -LiteralPath $Path -Name $Name -Value $Value -PropertyType DWord -Force -ErrorAction Stop | Out-Null + + $actual = (Get-ItemProperty -LiteralPath $Path -Name $Name -ErrorAction Stop).$Name + if ($actual -ne $Value) { + throw "Verification failed for $Path\$Name. Expected $Value, read back '$actual'." } - Write-Log "Stack Trace: $($_.ScriptStackTrace)" + Write-ScriptLog "Verified $Path\$Name = $actual" } -# Section 2: Disable Auto-lock upon Smart Card Removal -# This section modifies the registry to prevent automatic screen lock when smart card is removed +# Start logging +Write-ScriptLog "Begin..." +Write-ScriptLog $SectionLine +if ($KeepLogs) { + Write-ScriptLog "-KeepLogs was given. It has no effect: the log file is always kept." +} -try -{ - # Check if the Winlogon registry path exists - # This path contains Windows logon configuration settings - if (-NOT (Test-Path -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon')) { - # Registry path doesn't exist - create it - Write-Log "Reg path not found, hence creating Reg path HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" - New-Item -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' -Force -ErrorAction SilentlyContinue | Out-Null - } - - # Set the ScRemoveOption registry value to 0 - # Value 0 = Do not lock workstation when smart card is removed - # Value 1 = Lock workstation when smart card is removed - if ($PSCmdlet.ShouldProcess('HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\ScRemoveOption', 'Set value to 0 (do not lock on smart card removal)')) { - Write-Log "Reg path HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon found, updating Reg key ScRemoveOption with value 0" - New-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' -Name 'ScRemoveOption' -Value 0 -Force -ErrorAction SilentlyContinue | Out-Null - Write-Log "Reg key value updated" - } +$failures = @() + +# Section 1: allow password logon +try { + # 0 = allow password logon, 1 = require smart card + Set-RegistryDwordVerified -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' -Name 'scforceoption' -Value 0 -Description 'Set value to 0 (allow password logon)' } -catch -{ - # Log any errors that occur during registry modification with enhanced details - $errMsg = $_.Exception.Message - Write-Log "Error: $errMsg" - if ($_.Exception.InnerException) { - Write-Log "Inner Exception: $($_.Exception.InnerException.Message)" - } - Write-Log "Stack Trace: $($_.ScriptStackTrace)" +catch { + $failures += "scforceoption: $($_.Exception.Message)" + Write-ScriptLog "Error: scforceoption: $($_.Exception.Message)" } -# Section 3: Disable Smart Card Policy Service -# This section disables the Smart Card Policy Service by setting its startup type to Disabled +# Section 2: do not lock the workstation when the smart card is removed +try { + # 0 = do nothing, 1 = lock workstation + Set-RegistryDwordVerified -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' -Name 'ScRemoveOption' -Value 0 -Description 'Set value to 0 (do not lock on smart card removal)' +} +catch { + $failures += "ScRemoveOption: $($_.Exception.Message)" + Write-ScriptLog "Error: ScRemoveOption: $($_.Exception.Message)" +} -try -{ - # Check if the Smart Card Policy Service registry path exists - # This path contains service configuration for SCPolicySvc - if (-NOT (Test-Path -LiteralPath 'HKLM:\SYSTEM\CurrentControlSet\Services\SCPolicySvc')) { - # Registry path doesn't exist - create it - Write-Log "Reg path not found, hence creating Reg path HKLM:\SYSTEM\CurrentControlSet\Services\SCPolicySvc" - New-Item -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\SCPolicySvc' -Force -ErrorAction SilentlyContinue | Out-Null +# Section 3: Smart Card Policy Service startup type +try { + $serviceKey = 'HKLM:\SYSTEM\CurrentControlSet\Services\SCPolicySvc' + if (-not (Test-Path -LiteralPath $serviceKey)) { + # Nothing to disable. Do not create a bare service key: that leaves a phantom service entry. + Write-ScriptLog "Service key $serviceKey does not exist, so there is no service to disable. Skipped." } - - # Set the Start registry value to 4 (Disabled) - # Service startup types: 0=Boot, 1=System, 2=Auto, 3=Manual, 4=Disabled - # Setting to 4 (Disabled) prevents the service from starting - if ($PSCmdlet.ShouldProcess('HKLM:\SYSTEM\CurrentControlSet\Services\SCPolicySvc', 'Set Start value to 4 (Disabled) and disable SCPolicySvc')) { - Write-Log "Reg path HKLM:\SYSTEM\CurrentControlSet\Services\SCPolicySvc found, updating Reg key Start with value 4" - New-ItemProperty -LiteralPath 'HKLM:\SYSTEM\CurrentControlSet\Services\SCPolicySvc' -Name 'Start' -Value 4 -Force -ErrorAction SilentlyContinue | Out-Null - Write-Log "Reg key value updated" - - # Also set the service startup type using Set-Service to ensure immediate effect - try { - Set-Service -Name "SCPolicySvc" -StartupType Disabled -ErrorAction SilentlyContinue - Write-Log "Service startup type set to Disabled using Set-Service" - } - catch { - Write-Log "Warning: Could not set service startup type using Set-Service: $($_.Exception.Message)" + else { + # Service startup types: 0=Boot, 1=System, 2=Auto, 3=Manual, 4=Disabled + Set-RegistryDwordVerified -Path $serviceKey -Name 'Start' -Value 4 -Description 'Set Start value to 4 (Disabled) for SCPolicySvc' + + if ($PSCmdlet.ShouldProcess('SCPolicySvc', 'Set service startup type to Disabled')) { + Set-Service -Name 'SCPolicySvc' -StartupType Disabled -ErrorAction Stop + $startType = (Get-Service -Name 'SCPolicySvc' -ErrorAction Stop).StartType + if ("$startType" -ne 'Disabled') { + throw "SCPolicySvc startup type reads '$startType' after Set-Service, expected Disabled." + } + Write-ScriptLog "Service startup type set to Disabled and verified" } } } -catch -{ - # Log any errors that occur during registry modification with enhanced details - $errMsg = $_.Exception.Message - Write-Log "Error: $errMsg" - if ($_.Exception.InnerException) { - Write-Log "Inner Exception: $($_.Exception.InnerException.Message)" - } - Write-Log "Stack Trace: $($_.ScriptStackTrace)" +catch { + $failures += "SCPolicySvc: $($_.Exception.Message)" + Write-ScriptLog "Error: SCPolicySvc: $($_.Exception.Message)" } -# Cleanup: Remove the log file after script execution -# This is done to clean up temporary log files -# -ErrorAction SilentlyContinue prevents errors if the file doesn't exist -# Only remove if -KeepLogs is not specified -if (-not $WhatIfPreference -and -not $KeepLogs) { - $logFilePath = Join-Path $Log_Path $Log_FileName - Remove-Item -Path $logFilePath -Force -ErrorAction SilentlyContinue +# The log file is kept on purpose: it is the audit trail for a security setting change. +if ($WhatIfPreference) { + Write-Host "WhatIf: no changes were made." + exit 0 } -elseif ($KeepLogs) { - $logFilePath = Join-Path $Log_Path $Log_FileName - Write-Log "Log file kept at: $logFilePath" + +if ($failures.Count -gt 0) { + Write-ScriptLog "Script finished with $($failures.Count) failure(s): $($failures -join ' | ')" + Write-Error "Smart card enforcement was NOT fully removed: $($failures -join ' | ')" + exit 1 } -# Log completion and exit with success code -Write-Log "Script completed successfully." +Write-ScriptLog "Script completed successfully. All changes were applied and verified." exit 0 diff --git a/Security/Enable-PrintSpoolerService.ps1 b/Security/Enable-PrintSpoolerService.ps1 index 3517926..cb28066 100644 --- a/Security/Enable-PrintSpoolerService.ps1 +++ b/Security/Enable-PrintSpoolerService.ps1 @@ -61,11 +61,7 @@ try { Set-Service -name "Spooler" -startupType "Automatic" -ErrorAction Stop Write-Host "Print Spooler startup type set to Automatic successfully." -ForegroundColor Green - # Wait 10 seconds to allow the service configuration to be applied - # This ensures the service is ready to be started - Write-Host "Waiting for service configuration to be applied..." -ForegroundColor Yellow - Start-Sleep -Seconds 10 - + # Set-Service has applied the startup type by the time it returns, so no wait is needed # Start the Print Spooler service # This makes the service immediately available without requiring a reboot Write-Host "Starting Print Spooler service..." -ForegroundColor Yellow diff --git a/Security/Enable-SmartCardLogonEnforcement.ps1 b/Security/Enable-SmartCardLogonEnforcement.ps1 index ed2b0b4..e0cad2c 100644 --- a/Security/Enable-SmartCardLogonEnforcement.ps1 +++ b/Security/Enable-SmartCardLogonEnforcement.ps1 @@ -10,9 +10,30 @@ interactive logon and enables automatic lock on smart card removal. The script also enables the Smart Card Policy Service. + WARNING: "Interactive logon: Require smart card" (scforceoption = 1) blocks password logon + for EVERY account on the device, including the local administrator. A device that has no + smart card reader, no card or no certificate-based logon set up can be locked out for good. + + To prevent that, the script runs a preflight check before it writes anything. It refuses to + continue (exit 1, nothing changed) unless the Smart Card Policy Service exists and at least one + smart card reader is present and healthy. The check cannot prove that a user has a card or a + logon certificate, so confirm that separately. Use -Force only for a deliberate, supervised run + where you accept the lockout risk. + + Every registry write uses -ErrorAction Stop and is read back after it is written. If any write + or read-back fails the script exits 1. The log file is always kept. + + Recovery if a device is locked out: boot to Windows Recovery, load the device's + SOFTWARE hive in regedit and set + HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\scforceoption to 0, or push + Disable-SmartCardLogonEnforcement.ps1 through Intune to a device that can still check in. + .PARAMETER KeepLogs - Keeps the log file after script execution instead of removing it. - Useful for troubleshooting purposes. + Retained so existing callers keep working. It has no effect: the log file is always kept now, + because this script changes a security setting and should leave an audit trail. + +.PARAMETER Force + Skips the smart card reader preflight check. Lockout risk applies. .EXAMPLE .\Enable-SmartCardLogonEnforcement.ps1 @@ -21,204 +42,272 @@ .\Enable-SmartCardLogonEnforcement.ps1 -WhatIf .EXAMPLE - .\Enable-SmartCardLogonEnforcement.ps1 -KeepLogs + .\Enable-SmartCardLogonEnforcement.ps1 -Force .NOTES Requires: Administrator privileges - Modifies: HKLM registry keys + Modifies: HKLM registry keys, SCPolicySvc startup type + Log: %ProgramData%\Microsoft\IntuneManagementExtension\Logs\win32-Enable_SmartCardLogon_Enforcement.log + Exit Codes: + - 0: All changes applied and verified, or a -WhatIf run + - 1: Preflight refused, a change failed, or verification failed #> [CmdletBinding(SupportsShouldProcess=$true)] param( [Parameter(Mandatory=$false)] - [switch]$KeepLogs + [switch]$KeepLogs, + + [Parameter(Mandatory=$false)] + [switch]$Force ) -# Architecture check: If running as a 32-bit process on an x64 system, re-launch as a 64-bit process -# This ensures registry modifications are made to the correct registry hive (64-bit vs 32-bit) -# PROCESSOR_ARCHITEW6432 is set on 64-bit systems when running 32-bit processes +# Build the argument list used to relaunch this script in 64-bit PowerShell. +# Every switch that was passed (-WhatIf, -Verbose, -KeepLogs, -Force) is forwarded, so the child +# does what the caller asked. Dropping -WhatIf here would make the 64-bit child change the machine. +function Get-RelaunchArgumentList { + [CmdletBinding()] + param( + [Parameter(Mandatory=$true)] + [string]$ScriptPath, + + [Parameter(Mandatory=$false)] + [hashtable]$BoundParameters = @{} + ) + + $arguments = @('-ExecutionPolicy', 'Bypass', '-NoProfile', '-File', $ScriptPath) + foreach ($key in $BoundParameters.Keys) { + $value = $BoundParameters[$key] + if ($value -is [System.Management.Automation.SwitchParameter]) { + if ($value.IsPresent) { $arguments += "-$key" } + } + } + return $arguments +} + +# Architecture check: if running as a 32-bit process on a 64-bit system, relaunch as 64-bit +# so registry writes go to the 64-bit hive. PROCESSOR_ARCHITEW6432 is set for 32-bit processes on 64-bit Windows. if ($env:PROCESSOR_ARCHITEW6432 -and $env:PROCESSOR_ARCHITEW6432 -ne "ARM64") { - # Check if the 64-bit PowerShell executable exists in the SysNative path - # SysNative is a special path that allows 32-bit processes to access 64-bit system files - if (Test-Path "$($env:WINDIR)\SysNative\WindowsPowerShell\v1.0\powershell.exe") + # SysNative lets a 32-bit process reach the 64-bit system files + $sysNativePowerShell = "$($env:WINDIR)\SysNative\WindowsPowerShell\v1.0\powershell.exe" + if (Test-Path $sysNativePowerShell) { - # Re-launch the script in 64-bit PowerShell - # -ExecutionPolicy bypass: Allows script execution regardless of execution policy - # -NoProfile: Starts PowerShell without loading user profile (faster startup) - # -File: Specifies the script file to execute - & "$($env:WINDIR)\SysNative\WindowsPowerShell\v1.0\powershell.exe" -ExecutionPolicy bypass -NoProfile -File "$PSCommandPath" - # Exit with the same exit code as the re-launched script + $relaunchArguments = Get-RelaunchArgumentList -ScriptPath $PSCommandPath -BoundParameters $PSBoundParameters + & $sysNativePowerShell @relaunchArguments exit $LASTEXITCODE } } - -# Logging Preparation Section -# Set up variables for logging script execution to a log file -# Define the application name for log file naming +# Logging Preparation Section $AppName = "Enable_SmartCardLogon_Enforcement" - -# Construct the log file name using Intune naming convention $Log_FileName = "win32-$AppName.log" - -# Define the log file path (Intune Management Extension logs directory) -# Use environment variable for cross-system compatibility $Log_Path = Join-Path $env:ProgramData "Microsoft\IntuneManagementExtension\Logs" +$TestPath = Join-Path $Log_Path $Log_FileName +$SectionLine = "* * " * 10 -# Construct the full path to the log file -$TestPath = "$Log_Path\$Log_FileName" - -# Define a section line separator for log readability (asterisks repeated 10 times) -$SectionLine="* * "*10 - -# Check if the log file exists, create it if it doesn't -# This ensures logging can proceed even if the file doesn't exist -If(!(Test-Path $TestPath)) -{ - # Create the log file in the Intune logs directory - New-Item -Path $Log_Path -Name $Log_FileName -ItemType "File" -Force -} - -# Define a logging function to write timestamped messages to the log file -function Write-Log { +# Write a timestamped message to the log file and to the console. +# Under -WhatIf nothing is written to disk, so a dry run leaves no files behind. +function Write-ScriptLog { [CmdletBinding()] param( [Parameter()] - [string]$Message # The message to write to the log + [string]$Message ) - # Get current date and time formatted as "DayOfWeek MM/dd/yyyy HH:mm:ss" $timestamp = Get-Date -Format "dddd MM/dd/yyyy HH:mm:ss" - # Append the timestamped message to the log file - Add-Content -Path $TestPath -Value "$timestamp : $Message" + if ($WhatIfPreference) { + Write-Host "[log] $Message" + return + } + try { + if (-not (Test-Path -Path $Log_Path)) { + New-Item -Path $Log_Path -ItemType Directory -Force -ErrorAction Stop | Out-Null + } + Add-Content -Path $TestPath -Value "$timestamp : $Message" -ErrorAction Stop + } + catch { + Write-Warning "Could not write to log file ${TestPath}: $($_.Exception.Message)" + } } -# Start logging - write initial log entries -# This log file can also be used by Intune Management Extension for detection -Write-Log "Begin..." -Write-Log $SectionLine +# Set one DWORD registry value and read it back. Throws if the write or the read-back fails. +# Creates the key only when it is missing, and only when the change is confirmed (-WhatIf creates nothing). +function Set-RegistryDwordVerified { + [CmdletBinding(SupportsShouldProcess=$true)] + param( + [Parameter(Mandatory=$true)] + [string]$Path, -# Section 1: Enable Smart Card Logon Enforcement -# This section modifies the registry to require smart card for interactive logon + [Parameter(Mandatory=$true)] + [string]$Name, -try -{ - # Check if the System policies registry path exists - # This path contains policy settings including smart card enforcement - if (-NOT (Test-Path -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System')) { - # Registry path doesn't exist - create it - Write-Log "Reg path not found, hence creating Reg path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" - New-Item -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' -Force -ErrorAction SilentlyContinue | Out-Null - } - - # Set the scforceoption registry value to 1 - # Value 0 = Allow password logon (smart card not required) - # Value 1 = Require smart card for interactive logon - if ($PSCmdlet.ShouldProcess('HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\scforceoption', 'Set value to 1 (require smart card for interactive logon)')) { - Write-Log "Reg path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System found, updating Reg key scforceoption with value 1" - New-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' -Name 'scforceoption' -Value 1 -Force -ErrorAction SilentlyContinue | Out-Null - Write-Log "Reg key value updated" - } -} -catch -{ - # Log any errors that occur during registry modification with enhanced details - $errMsg = $_.Exception.Message - Write-Log "Error: $errMsg" - if ($_.Exception.InnerException) { - Write-Log "Inner Exception: $($_.Exception.InnerException.Message)" + [Parameter(Mandatory=$true)] + [int]$Value, + + [Parameter(Mandatory=$true)] + [string]$Description + ) + + if (-not $PSCmdlet.ShouldProcess("$Path\$Name", $Description)) { + return + } + + if (-not (Test-Path -LiteralPath $Path)) { + Write-ScriptLog "Reg path $Path not found, creating it" + New-Item -Path $Path -Force -ErrorAction Stop | Out-Null } - Write-Log "Stack Trace: $($_.ScriptStackTrace)" + + Write-ScriptLog "Setting $Path\$Name to $Value" + New-ItemProperty -LiteralPath $Path -Name $Name -Value $Value -PropertyType DWord -Force -ErrorAction Stop | Out-Null + + $actual = (Get-ItemProperty -LiteralPath $Path -Name $Name -ErrorAction Stop).$Name + if ($actual -ne $Value) { + throw "Verification failed for $Path\$Name. Expected $Value, read back '$actual'." + } + Write-ScriptLog "Verified $Path\$Name = $actual" } -# Section 2: Enable Auto-lock upon Smart Card Removal -# This section modifies the registry to automatically lock the screen when smart card is removed +# Preflight for the Enable script: is there any chance a user can still log on after enforcement? +# Returns an object with Ready and a list of Reasons it is not. It cannot see cards or logon +# certificates, only that the platform pieces exist. +function Test-SmartCardLogonReady { + [CmdletBinding()] + param() -try -{ - # Check if the Winlogon registry path exists - # This path contains Windows logon configuration settings - if (-NOT (Test-Path -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon')) { - # Registry path doesn't exist - create it - Write-Log "Reg path not found, hence creating Reg path HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" - New-Item -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' -Force -ErrorAction SilentlyContinue | Out-Null - } - - # Set the ScRemoveOption registry value to 1 - # Value 0 = Do not lock workstation when smart card is removed - # Value 1 = Lock workstation when smart card is removed - if ($PSCmdlet.ShouldProcess('HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\ScRemoveOption', 'Set value to 1 (lock workstation on smart card removal)')) { - Write-Log "Reg path HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon found, updating Reg key ScRemoveOption with value 1" - New-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' -Name 'ScRemoveOption' -Value 1 -Force -ErrorAction SilentlyContinue | Out-Null - Write-Log "Reg key value updated" - } -} -catch -{ - # Log any errors that occur during registry modification with enhanced details - $errMsg = $_.Exception.Message - Write-Log "Error: $errMsg" - if ($_.Exception.InnerException) { - Write-Log "Inner Exception: $($_.Exception.InnerException.Message)" + $reasons = @() + + if (-not (Test-Path -LiteralPath 'HKLM:\SYSTEM\CurrentControlSet\Services\SCPolicySvc')) { + $reasons += "The Smart Card Policy Service (SCPolicySvc) is not installed." + } + + $readers = @() + try { + $readers = @(Get-CimInstance -ClassName Win32_PnPEntity -Filter "PNPClass='SmartCardReader'" -ErrorAction Stop | + Where-Object { $_.Status -eq 'OK' }) + } + catch { + $reasons += "Could not enumerate smart card readers: $($_.Exception.Message)" + } + if ($readers.Count -eq 0) { + $reasons += "No working smart card reader was found." + } + + [PSCustomObject]@{ + Ready = ($reasons.Count -eq 0) + Reasons = $reasons + Readers = @($readers | ForEach-Object { $_.Name }) } - Write-Log "Stack Trace: $($_.ScriptStackTrace)" } -# Section 3: Enable Smart Card Policy Service -# This section enables the Smart Card Policy Service by setting its startup type to Automatic +# Start logging +Write-ScriptLog "Begin..." +Write-ScriptLog $SectionLine +if ($KeepLogs) { + Write-ScriptLog "-KeepLogs was given. It has no effect: the log file is always kept." +} + +$failures = @() + +# Preflight: refuse before any change if the device could be locked out +$preflight = Test-SmartCardLogonReady +if ($preflight.Ready) { + Write-ScriptLog "Preflight passed. Smart card reader(s): $($preflight.Readers -join ', ')" +} +elseif ($Force) { + Write-ScriptLog "Preflight failed but -Force was given, continuing: $($preflight.Reasons -join ' ')" + Write-Warning "Preflight failed but -Force was given. Lockout risk applies: $($preflight.Reasons -join ' ')" +} +else { + $why = $preflight.Reasons -join ' ' + Write-ScriptLog "Preflight refused. $why No changes were made." + if ($WhatIfPreference) { + Write-Host "WhatIf: a real run would refuse and exit 1. $why" + exit 0 + } + Write-Error "Refusing to require smart card logon: $why Enforcing it on a device with no working reader can lock every user out, including the local administrator. Fix the above or use -Force on a supervised run." + exit 1 +} + +# Step 1: lock the workstation when the smart card is removed +try { + # 0 = do nothing, 1 = lock workstation + Set-RegistryDwordVerified -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' -Name 'ScRemoveOption' -Value 1 -Description 'Set value to 1 (lock workstation on smart card removal)' +} +catch { + $failures += "ScRemoveOption: $($_.Exception.Message)" + Write-ScriptLog "Error: ScRemoveOption: $($_.Exception.Message)" +} + +# Step 2: Smart Card Policy Service startup type +try { + $serviceKey = 'HKLM:\SYSTEM\CurrentControlSet\Services\SCPolicySvc' + if (-not (Test-Path -LiteralPath $serviceKey)) { + # Do not create a bare service key: that leaves a phantom service entry with only a Start value. + throw "Service key $serviceKey does not exist, so SCPolicySvc cannot be enabled. Nothing was created." + } -try -{ - # Check if the Smart Card Policy Service registry path exists - # This path contains service configuration for SCPolicySvc - if (-NOT (Test-Path -LiteralPath 'HKLM:\SYSTEM\CurrentControlSet\Services\SCPolicySvc')) { - # Registry path doesn't exist - create it - Write-Log "Reg path not found, hence creating Reg path HKLM:\SYSTEM\CurrentControlSet\Services\SCPolicySvc" - New-Item -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\SCPolicySvc' -Force -ErrorAction SilentlyContinue | Out-Null - } - - # Set the Start registry value to 2 (Automatic) # Service startup types: 0=Boot, 1=System, 2=Auto, 3=Manual, 4=Disabled - # Setting to 2 (Automatic) ensures the service starts automatically on boot - if ($PSCmdlet.ShouldProcess('HKLM:\SYSTEM\CurrentControlSet\Services\SCPolicySvc', 'Set Start value to 2 (Automatic) and enable SCPolicySvc')) { - Write-Log "Reg path HKLM:\SYSTEM\CurrentControlSet\Services\SCPolicySvc found, updating Reg key Start with value 2" - New-ItemProperty -LiteralPath 'HKLM:\SYSTEM\CurrentControlSet\Services\SCPolicySvc' -Name 'Start' -Value 2 -Force -ErrorAction SilentlyContinue | Out-Null - Write-Log "Reg key value updated" + Set-RegistryDwordVerified -Path $serviceKey -Name 'Start' -Value 2 -Description 'Set Start value to 2 (Automatic) for SCPolicySvc' + + if ($PSCmdlet.ShouldProcess('SCPolicySvc', 'Set service startup type to Automatic')) { + Set-Service -Name 'SCPolicySvc' -StartupType Automatic -ErrorAction Stop + $startType = (Get-Service -Name 'SCPolicySvc' -ErrorAction Stop).StartType + if ("$startType" -ne 'Automatic') { + throw "SCPolicySvc startup type reads '$startType' after Set-Service, expected Automatic." + } + Write-ScriptLog "Service startup type set to Automatic and verified" + } +} +catch { + $failures += "SCPolicySvc: $($_.Exception.Message)" + Write-ScriptLog "Error: SCPolicySvc: $($_.Exception.Message)" +} - # Also set the service startup type using Set-Service to ensure immediate effect +# Step 3, LAST: require a smart card for interactive logon. +# This is the setting that blocks password logon, so it is written only after every other step succeeded. +# If any earlier step failed it is not written at all. If its own write or read-back fails, the value that was +# there before is put back, so a half-applied run never leaves the device requiring a card. +if ($failures.Count -gt 0) { + Write-ScriptLog "Not enforcing smart card logon because an earlier step failed: $($failures -join ' | ')" +} +else { + $enforceKey = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' + $previousEnforce = $null + if (-not $WhatIfPreference) { + $existing = Get-ItemProperty -LiteralPath $enforceKey -Name 'scforceoption' -ErrorAction SilentlyContinue + if ($existing -and $existing.PSObject.Properties['scforceoption']) { $previousEnforce = $existing.scforceoption } + } + try { + # 0 = allow password logon, 1 = require smart card + Set-RegistryDwordVerified -Path $enforceKey -Name 'scforceoption' -Value 1 -Description 'Set value to 1 (require smart card for interactive logon)' + } + catch { + $failures += "scforceoption: $($_.Exception.Message)" + Write-ScriptLog "Error: scforceoption: $($_.Exception.Message)" + # Roll back to the previous value, or to 0 (the Windows default, password logon allowed) if there was none + $restore = if ($null -ne $previousEnforce) { [int]$previousEnforce } else { 0 } try { - Set-Service -Name "SCPolicySvc" -StartupType Automatic -ErrorAction SilentlyContinue - Write-Log "Service startup type set to Automatic using Set-Service" + New-ItemProperty -LiteralPath $enforceKey -Name 'scforceoption' -Value $restore -PropertyType DWord -Force -ErrorAction Stop | Out-Null + Write-ScriptLog "Rolled scforceoption back to $restore" } catch { - Write-Log "Warning: Could not set service startup type using Set-Service: $($_.Exception.Message)" + $failures += "scforceoption rollback: $($_.Exception.Message)" + Write-ScriptLog "ERROR: could not roll scforceoption back to $restore : $($_.Exception.Message)" } } } -catch -{ - # Log any errors that occur during registry modification with enhanced details - $errMsg = $_.Exception.Message - Write-Log "Error: $errMsg" - if ($_.Exception.InnerException) { - Write-Log "Inner Exception: $($_.Exception.InnerException.Message)" - } - Write-Log "Stack Trace: $($_.ScriptStackTrace)" -} -# Cleanup: Remove the log file after script execution -# This is done to clean up temporary log files -# -ErrorAction SilentlyContinue prevents errors if the file doesn't exist -# Only remove if -KeepLogs is not specified -if (-not $WhatIfPreference -and -not $KeepLogs) { - $logFilePath = Join-Path $Log_Path $Log_FileName - Remove-Item -Path $logFilePath -Force -ErrorAction SilentlyContinue +# The log file is kept on purpose: it is the audit trail for a security setting change. +if ($WhatIfPreference) { + Write-Host "WhatIf: no changes were made." + exit 0 } -elseif ($KeepLogs) { - $logFilePath = Join-Path $Log_Path $Log_FileName - Write-Log "Log file kept at: $logFilePath" + +if ($failures.Count -gt 0) { + Write-ScriptLog "Script finished with $($failures.Count) failure(s): $($failures -join ' | ')" + Write-Error "Smart card enforcement was NOT fully applied: $($failures -join ' | ')" + exit 1 } -# Log completion and exit with success code -Write-Log "Script completed successfully." +Write-ScriptLog "Script completed successfully. All changes were applied and verified." exit 0 diff --git a/Tests/Detect-OfficeUpdateChannel.Tests.ps1 b/Tests/Detect-OfficeUpdateChannel.Tests.ps1 new file mode 100644 index 0000000..9533985 --- /dev/null +++ b/Tests/Detect-OfficeUpdateChannel.Tests.ps1 @@ -0,0 +1,90 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '5.0.0' } + +# Tests for Detection/Detect-OfficeUpdateChannel.ps1 (audit finding M2, M4). +# Intune Remediations contract: exit 0 = no remediation needed, exit 1 = run the remediation. + +. (Join-Path $PSScriptRoot 'TestHelpers.ps1') + +BeforeAll { + . (Join-Path $PSScriptRoot 'TestHelpers.ps1') + $script:ScriptPath = Get-RepoPath 'Detection\Detect-OfficeUpdateChannel.ps1' + $script:CurrentCdn = 'http://officecdn.microsoft.com/pr/492350f6-3a01-4f97-b9c0-c7c6ddf67d60' + $script:SemiAnnualCdn = 'http://officecdn.microsoft.com/pr/7ffbc6bf-bc32-4f92-8982-f9dd17fd3114' + function New-ReleasePayload { + @( + [PSCustomObject]@{ channelId = 'Current'; latestversion = '16.0.99999.1'; officeVersions = @([PSCustomObject]@{ cdnBaseUrl = $script:CurrentCdn }) }, + [PSCustomObject]@{ channelId = 'SemiAnnual'; latestversion = '16.0.17928.20700'; officeVersions = @(1..15 | ForEach-Object { [PSCustomObject]@{ cdnBaseUrl = $script:SemiAnnualCdn } }) } + ) + } + function Invoke-Under { Invoke-ScriptUnderTest -Path $script:ScriptPath } +} + +Describe 'Detect-OfficeUpdateChannel.ps1' { + BeforeEach { + if ($env:PROCESSOR_ARCHITEW6432) { throw 'This test must not run in a 32-bit host.' } + foreach ($c in $script:StateChangingCommands) { Mock -CommandName $c -MockWith ([scriptblock]::Create("throw 'UNMOCKED state-changing call: $c'")) } + + $global:IntuneTestState = @{ + Reg = @{ CDNBaseUrl = $script:SemiAnnualCdn; VersionToReport = '16.0.17928.20700' } + C2RInstalled = $true + Payload = (New-ReleasePayload) + ApiFails = $false + } + Mock Test-Path { $global:IntuneTestState.C2RInstalled } + Mock Get-ItemPropertyValue { $global:IntuneTestState.Reg[$Name] } + Mock Invoke-RestMethod { if ($global:IntuneTestState.ApiFails) { throw 'network down' } $global:IntuneTestState.Payload } + Mock Start-Sleep { } + } + AfterEach { Remove-Variable -Name IntuneTestState -Scope Global -ErrorAction SilentlyContinue } + + It 'exits 0 when on Semi-Annual and the latest version' { + $r = Invoke-Under + $r.ExitCode | Should -Be 0 + $r.Output | Should -Match 'Compliant' + } + + It 'exits 1 and names the channel when not on Semi-Annual' { + $global:IntuneTestState.Reg['CDNBaseUrl'] = $script:CurrentCdn + $r = Invoke-Under + $r.ExitCode | Should -Be 1 + $r.Output | Should -Match 'not using the Semi-Annual channel' + $r.Output | Should -Match 'Current Channel' + } + + It 'exits 1 and says it is BEHIND, not on the wrong channel, when Semi-Annual but old (M4)' { + $global:IntuneTestState.Reg['VersionToReport'] = '16.0.1.1' + $r = Invoke-Under + $r.ExitCode | Should -Be 1 + $r.Output | Should -Match 'behind' + $r.Output | Should -Not -Match 'not using the Semi-Annual channel' + } + + It 'exits 0 as not applicable when Click-to-Run is not installed (M4)' { + $global:IntuneTestState.C2RInstalled = $false + $r = Invoke-Under + $r.ExitCode | Should -Be 0 + $r.Output | Should -Match 'Not applicable' + Should -Invoke Invoke-RestMethod -Times 0 -Exactly + } + + It 'exits 0 with "Cannot determine" when the releases service is unreachable (M4)' { + $global:IntuneTestState.ApiFails = $true + $r = Invoke-Under + $r.ExitCode | Should -Be 0 + $r.Output | Should -Match 'Cannot determine' + } + + It 'exits 1 when the local CDN URL is not a Microsoft-listed channel' { + $global:IntuneTestState.Reg['CDNBaseUrl'] = 'http://example.invalid/custom' + (Invoke-Under).ExitCode | Should -Be 1 + } +} + +Describe 'Detect-OfficeUpdateChannel.ps1 relaunch arguments (M2)' { + BeforeAll { + . ([scriptblock]::Create((Import-ScriptFunction -Path $script:ScriptPath -Name 'Get-RelaunchArgumentList'))) + } + It 'forwards -Verbose to the 64-bit child' { + Get-RelaunchArgumentList -ScriptPath 'C:\x\d.ps1' -BoundParameters @{ Verbose = [switch]$true } | Should -Contain '-Verbose' + } +} diff --git a/Tests/Export-IntuneDeviceReport.Tests.ps1 b/Tests/Export-IntuneDeviceReport.Tests.ps1 new file mode 100644 index 0000000..eecbbb1 --- /dev/null +++ b/Tests/Export-IntuneDeviceReport.Tests.ps1 @@ -0,0 +1,92 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '5.0.0' } + +# Tests for Reporting/Export-IntuneDeviceReport.ps1 (audit findings H5, M6, M7, M8, L3). + +. (Join-Path $PSScriptRoot 'TestHelpers.ps1') + +BeforeAll { + . (Join-Path $PSScriptRoot 'TestHelpers.ps1') + $script:ScriptPath = Get-RepoPath 'Reporting\Export-IntuneDeviceReport.ps1' + Import-Module (Get-ModuleManifestPath) -Force + $script:Dev = { param($Id, $Name) [PSCustomObject]@{ id = $Id; deviceName = $Name; userPrincipalName = 'u@example.test'; complianceState = 'compliant' } } +} + +Describe 'Export-IntuneDeviceReport.ps1' { + BeforeEach { + $global:IntuneTestState = New-GraphTestState + Mock Invoke-RestMethod -ModuleName IntuneCommon -MockWith $script:GraphMockBody + Mock Start-Sleep -ModuleName IntuneCommon { } + Mock Install-Module { throw 'Install-Module must never be called' } + $script:out = Join-Path $TestDrive 'report.csv' + if (Test-Path $script:out) { Remove-Item $script:out } + $script:creds = @{ AppId = 'app-id'; TenantId = 'tenant-id'; ClientSecret = 'plain-secret' } + Remove-Item Env:\INTUNE_APP_ID, Env:\INTUNE_TENANT_ID, Env:\INTUNE_CLIENT_SECRET -ErrorAction SilentlyContinue + } + AfterEach { Remove-Variable -Name IntuneTestState -Scope Global -ErrorAction SilentlyContinue } + + It 'lists per-device compliance and configuration states and exits 0 (happy path)' { + Add-GraphRoute -Like '*/managedDevices' -Body (New-GraphPage @((& $script:Dev 'd1' 'PC-ONE'))) + Add-GraphRoute -Like "*managedDevices('d1')/deviceCompliancePolicyStates" -Body (New-GraphPage @([PSCustomObject]@{ displayName = 'Baseline' }, [PSCustomObject]@{ displayName = 'BitLocker' })) + Add-GraphRoute -Like "*managedDevices('d1')/deviceConfigurationStates" -Body (New-GraphPage @([PSCustomObject]@{ displayName = 'Wi-Fi' })) + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ OutputPath = $script:out }) + $r.ExitCode | Should -Be 0 + $row = Import-Csv $script:out + $row.CompliancePolicies | Should -Be 'Baseline; BitLocker' + $row.ConfigurationProfiles | Should -Be 'Wi-Fi' + $row.CollectionErrors | Should -BeNullOrEmpty + } + + It 'records a CollectionErrors value instead of silent blanks when a state call fails, and exits 1 (H5)' { + Add-GraphRoute -Like '*/managedDevices' -Body (New-GraphPage @((& $script:Dev 'd1' 'PC-ONE'))) + Add-GraphRoute -Like "*managedDevices('d1')/deviceCompliancePolicyStates" -Throw (New-HttpException -StatusCode 403 -Message 'Forbidden') + Add-GraphRoute -Like "*managedDevices('d1')/deviceConfigurationStates" -Body (New-GraphPage @([PSCustomObject]@{ displayName = 'Wi-Fi' })) + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ OutputPath = $script:out }) + $r.ExitCode | Should -Be 1 + $r.Output | Should -Match 'incomplete' + Test-Path $script:out | Should -BeTrue + $row = Import-Csv $script:out + $row.CollectionErrors | Should -Match 'compliance policy states: Forbidden' + $row.ConfigurationProfiles | Should -Be 'Wi-Fi' + } + + It 'treats an exhausted 429 as an error too, not as a blank (H5)' { + Add-GraphRoute -Like '*/managedDevices' -Body (New-GraphPage @((& $script:Dev 'd1' 'PC-ONE'))) + Add-GraphRoute -Like '*deviceCompliancePolicyStates' -Body (New-GraphPage @()) + Add-GraphRoute -Like '*deviceConfigurationStates' -Throw (New-HttpException -StatusCode 429 -Message 'Too Many Requests') + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ OutputPath = $script:out }) + $r.ExitCode | Should -Be 1 + (Import-Csv $script:out).CollectionErrors | Should -Match 'Too Many Requests' + } + + It 'pages through the device list (M8)' { + Add-GraphRoute -First -Like '*managedDevices?$skiptoken=2*' -Body (New-GraphPage @((& $script:Dev 'd2' 'PC-TWO'))) + Add-GraphRoute -Like '*/managedDevices' -Body (New-GraphPage @((& $script:Dev 'd1' 'PC-ONE')) -NextLink 'https://graph.microsoft.com/v1.0/deviceManagement/managedDevices?$skiptoken=2') + Add-GraphRoute -Like '*States' -Body (New-GraphPage @()) + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ OutputPath = $script:out }) + $r.ExitCode | Should -Be 0 + (Import-Csv $script:out).DeviceName | Should -Be @('PC-ONE', 'PC-TWO') + } + + It 'writes JSON with -Format JSON' { + $json = Join-Path $TestDrive 'report.json' + Add-GraphRoute -Like '*/managedDevices' -Body (New-GraphPage @((& $script:Dev 'd1' 'PC-ONE'))) + Add-GraphRoute -Like '*States' -Body (New-GraphPage @()) + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ OutputPath = $json; Format = 'JSON' }) + $r.ExitCode | Should -Be 0 + (Get-Content $json -Raw | ConvertFrom-Json).DeviceName | Should -Be 'PC-ONE' + } + + It 'neutralises a device name that starts with = in the CSV (L3)' { + Add-GraphRoute -Like '*/managedDevices' -Body (New-GraphPage @((& $script:Dev 'd1' '=cmd()'))) + Add-GraphRoute -Like '*States' -Body (New-GraphPage @()) + Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ OutputPath = $script:out }) | Out-Null + (Import-Csv $script:out).DeviceName | Should -Be "'=cmd()" + } + + It 'does not claim the Apps.Read.All permission it never uses (M7)' { + $text = Get-Content $script:ScriptPath -Raw + $text | Should -Not -Match 'DeviceManagementApps\.Read\.All and' + $text | Should -Match 'APPLICATION permissions' + $text | Should -Not -Match 'Install-Module' + } +} diff --git a/Tests/Get-IntuneAllAppsAssignmentDetails.Tests.ps1 b/Tests/Get-IntuneAllAppsAssignmentDetails.Tests.ps1 new file mode 100644 index 0000000..559599b --- /dev/null +++ b/Tests/Get-IntuneAllAppsAssignmentDetails.Tests.ps1 @@ -0,0 +1,111 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '5.0.0' } + +# Tests for Reporting/Get-IntuneAllAppsAssignmentDetails.ps1 (audit findings H6, M6, M7, M8, L3). + +. (Join-Path $PSScriptRoot 'TestHelpers.ps1') + +BeforeAll { + . (Join-Path $PSScriptRoot 'TestHelpers.ps1') + $script:ScriptPath = Get-RepoPath 'Reporting\Get-IntuneAllAppsAssignmentDetails.ps1' + Import-Module (Get-ModuleManifestPath) -Force + $script:Target = { param($Type, $GroupId) $t = [ordered]@{ '@odata.type' = $Type }; if ($GroupId) { $t.groupId = $GroupId }; [PSCustomObject]$t } + $script:Assign = { param($Intent, $Target) [PSCustomObject]@{ id = [guid]::NewGuid().ToString(); intent = $Intent; target = $Target } } + $script:App = { param($Name, $Assignments) [PSCustomObject]@{ id = $Name; displayName = $Name; '@odata.type' = '#microsoft.graph.win32LobApp'; displayVersion = '1.0'; assignments = @($Assignments) } } +} + +Describe 'Get-IntuneAllAppsAssignmentDetails.ps1' { + BeforeEach { + $global:IntuneTestState = New-GraphTestState + Mock Invoke-RestMethod -ModuleName IntuneCommon -MockWith $script:GraphMockBody + Mock Start-Sleep -ModuleName IntuneCommon { } + Mock Install-Module { throw 'Install-Module must never be called' } + $script:csv = Join-Path $TestDrive 'apps.csv' + if (Test-Path $script:csv) { Remove-Item $script:csv } + $script:creds = @{ AppId = 'app-id'; TenantId = 'tenant-id'; ClientSecret = 'plain-secret' } + Remove-Item Env:\INTUNE_APP_ID, Env:\INTUNE_TENANT_ID, Env:\INTUNE_CLIENT_SECRET -ErrorAction SilentlyContinue + } + AfterEach { Remove-Variable -Name IntuneTestState -Scope Global -ErrorAction SilentlyContinue } + + It 'has the -ExportCSVpath parameter the README documents (H6)' { + (Get-Command $script:ScriptPath).Parameters.Keys | Should -Contain 'ExportCSVpath' + } + + It 'writes to the path given in -ExportCSVpath (H6)' { + Add-GraphRoute -Like '*mobileApps?*' -Body (New-GraphPage @((& $script:App 'App One' @()))) + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ ExportCSVpath = $script:csv }) + $r.ExitCode | Should -Be 0 + Test-Path $script:csv | Should -BeTrue + } + + It 'labels exclusions as Excluded group, not as a targeted group (H6)' { + $assignments = @( + (& $script:Assign 'required' (& $script:Target '#microsoft.graph.groupAssignmentTarget' 'g-in')), + (& $script:Assign 'required' (& $script:Target '#microsoft.graph.exclusionGroupAssignmentTarget' 'g-out')), + (& $script:Assign 'available' (& $script:Target '#microsoft.graph.allLicensedUsersAssignmentTarget')), + (& $script:Assign 'required' (& $script:Target '#microsoft.graph.allDevicesAssignmentTarget')) + ) + Add-GraphRoute -Like '*mobileApps?*' -Body (New-GraphPage @((& $script:App 'App One' $assignments))) + Add-GraphRoute -Like '*/groups/g-in' -Body ([PSCustomObject]@{ displayName = 'Pilot' }) + Add-GraphRoute -Like '*/groups/g-out' -Body ([PSCustomObject]@{ displayName = 'Kiosks' }) + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ ExportCSVpath = $script:csv }) + $r.ExitCode | Should -Be 0 + $rows = Import-Csv $script:csv + $rows.Count | Should -Be 4 + $in = $rows | Where-Object Group -eq 'Pilot' + $in.TargetType | Should -Be 'Group' + $out = $rows | Where-Object Group -eq 'Kiosks' + $out.TargetType | Should -Be 'Excluded group' + ($rows | Where-Object TargetType -eq 'All Users').Group | Should -Be 'All Users' + ($rows | Where-Object TargetType -eq 'All Devices').Group | Should -Be 'All Devices' + } + + It 'gives an unassigned app one Not Assigned row' { + Add-GraphRoute -Like '*mobileApps?*' -Body (New-GraphPage @((& $script:App 'Lonely' @()))) + Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ ExportCSVpath = $script:csv }) | Out-Null + $row = Import-Csv $script:csv + $row.Group | Should -Be 'Not Assigned' + $row.TargetType | Should -Be 'None' + } + + It 'reads every page of apps instead of only the first (H6)' { + Add-GraphRoute -First -Like '*$skiptoken=2*' -Body (New-GraphPage @((& $script:App 'App Two' @()))) + Add-GraphRoute -Like '*mobileApps?*' -Body (New-GraphPage @((& $script:App 'App One' @())) -NextLink 'https://graph.microsoft.com/beta/deviceAppManagement/mobileApps?$expand=Assignments&$skiptoken=2') + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ ExportCSVpath = $script:csv }) + $r.ExitCode | Should -Be 0 + (Import-Csv $script:csv).Name | Should -Be @('App One', 'App Two') + } + + It 'resolves each group once, even when many assignments use it' { + $a = @(1..3 | ForEach-Object { & $script:Assign 'required' (& $script:Target '#microsoft.graph.groupAssignmentTarget' 'g1') }) + Add-GraphRoute -Like '*mobileApps?*' -Body (New-GraphPage @((& $script:App 'A' $a), (& $script:App 'B' $a))) + Add-GraphRoute -Like '*/groups/g1' -Body ([PSCustomObject]@{ displayName = 'G One' }) + Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ ExportCSVpath = $script:csv }) | Out-Null + @($global:IntuneTestState.Calls | Where-Object { $_.Uri -like '*/groups/g1' }).Count | Should -Be 1 + } + + It 'falls back to the group ID when the group lookup fails, and still exits 0' { + Add-GraphRoute -Like '*mobileApps?*' -Body (New-GraphPage @((& $script:App 'A' @((& $script:Assign 'required' (& $script:Target '#microsoft.graph.groupAssignmentTarget' 'gx')))))) + Add-GraphRoute -Like '*/groups/gx' -Throw (New-HttpException -StatusCode 404) + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ ExportCSVpath = $script:csv }) + $r.ExitCode | Should -Be 0 + (Import-Csv $script:csv).Group | Should -Be 'gx' + } + + It 'exits 1 when the app list request fails' { + Add-GraphRoute -Like '*mobileApps?*' -Throw (New-HttpException -StatusCode 403 -Message 'Forbidden') + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ ExportCSVpath = $script:csv }) + $r.ExitCode | Should -Be 1 + } + + It 'neutralises an app name that starts with = (L3)' { + Add-GraphRoute -Like '*mobileApps?*' -Body (New-GraphPage @((& $script:App '=cmd()' @()))) + Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ ExportCSVpath = $script:csv }) | Out-Null + (Import-Csv $script:csv).Name | Should -Be "'=cmd()" + } + + It 'uses no Microsoft.Graph SDK cmdlet and no plain-text-to-SecureString conversion (M6)' { + $text = Get-Content $script:ScriptPath -Raw + $text | Should -Not -Match 'Install-Module|Connect-MgGraph|Invoke-MgGraphRequest|Get-MgGroup|Disconnect-MgGraph' + $text | Should -Not -Match 'ConvertTo-SecureString' + } +} diff --git a/Tests/Get-IntuneDeviceCompliance.Tests.ps1 b/Tests/Get-IntuneDeviceCompliance.Tests.ps1 new file mode 100644 index 0000000..68fe11b --- /dev/null +++ b/Tests/Get-IntuneDeviceCompliance.Tests.ps1 @@ -0,0 +1,111 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '5.0.0' } + +# Tests for Reporting/Get-IntuneDeviceCompliance.ps1 (audit findings H5, M6, M8, L3, L4). +# Every Graph call goes through a mocked Invoke-RestMethod inside the IntuneCommon module. + +. (Join-Path $PSScriptRoot 'TestHelpers.ps1') + +BeforeAll { + . (Join-Path $PSScriptRoot 'TestHelpers.ps1') + $script:ScriptPath = Get-RepoPath 'Reporting\Get-IntuneDeviceCompliance.ps1' + Import-Module (Get-ModuleManifestPath) -Force + $script:Dev = { + param($Id, $Name, $Upn = 'u@example.test') + [PSCustomObject]@{ id = $Id; deviceName = $Name; userPrincipalName = $Upn; complianceState = 'compliant'; osVersion = '10.0'; managementAgent = 'mdm'; lastSyncDateTime = '2025-01-01T00:00:00Z' } + } +} + +Describe 'Get-IntuneDeviceCompliance.ps1' { + BeforeEach { + $global:IntuneTestState = New-GraphTestState + Mock Invoke-RestMethod -ModuleName IntuneCommon -MockWith $script:GraphMockBody + Mock Start-Sleep -ModuleName IntuneCommon { } + Mock Install-Module { throw 'Install-Module must never be called' } + $script:csv = Join-Path $TestDrive 'out.csv' + if (Test-Path $script:csv) { Remove-Item $script:csv } + $script:creds = @{ AppId = 'app-id'; TenantId = 'tenant-id'; ClientSecret = 'plain-secret' } + Remove-Item Env:\INTUNE_APP_ID, Env:\INTUNE_TENANT_ID, Env:\INTUNE_CLIENT_SECRET -ErrorAction SilentlyContinue + } + AfterEach { Remove-Variable -Name IntuneTestState -Scope Global -ErrorAction SilentlyContinue } + + It 'gives each device ITS OWN policy states, not the tenant-wide policy list (H5)' { + Add-GraphRoute -Like '*/managedDevices' -Body (New-GraphPage @((& $script:Dev 'd1' 'PC-ONE'), (& $script:Dev 'd2' 'PC-TWO'))) + Add-GraphRoute -Like "*managedDevices('d1')/deviceCompliancePolicyStates" -Body (New-GraphPage @([PSCustomObject]@{ displayName = 'Baseline'; state = 'compliant' }, [PSCustomObject]@{ displayName = 'BitLocker'; state = 'nonCompliant' })) + Add-GraphRoute -Like "*managedDevices('d2')/deviceCompliancePolicyStates" -Body (New-GraphPage @([PSCustomObject]@{ displayName = 'Baseline'; state = 'compliant' })) + # The tenant-wide list must not be what fills the column. A request for it would throw (no route). + + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ ExportPath = $script:csv }) + $r.ExitCode | Should -Be 0 + $rows = Import-Csv $script:csv + ($rows | Where-Object DeviceName -eq 'PC-ONE').CompliancePolicies | Should -Be 'Baseline (compliant); BitLocker (nonCompliant)' + ($rows | Where-Object DeviceName -eq 'PC-ONE').NonCompliantPolicies | Should -Be 'BitLocker' + ($rows | Where-Object DeviceName -eq 'PC-TWO').CompliancePolicies | Should -Be 'Baseline (compliant)' + ($rows | Where-Object DeviceName -eq 'PC-TWO').NonCompliantPolicies | Should -BeNullOrEmpty + $global:IntuneTestState.Calls.Uri | Should -Not -Contain 'https://graph.microsoft.com/v1.0/deviceManagement/deviceCompliancePolicies' + } + + It 'records a CollectionError, says the report is incomplete and exits 1 when a device state call fails (H5)' { + Add-GraphRoute -Like '*/managedDevices' -Body (New-GraphPage @((& $script:Dev 'd1' 'PC-ONE'), (& $script:Dev 'd2' 'PC-TWO'))) + Add-GraphRoute -Like "*managedDevices('d1')/deviceCompliancePolicyStates" -Throw (New-HttpException -StatusCode 403 -Message 'Forbidden') + Add-GraphRoute -Like "*managedDevices('d2')/deviceCompliancePolicyStates" -Body (New-GraphPage @([PSCustomObject]@{ displayName = 'Baseline'; state = 'compliant' })) + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ ExportPath = $script:csv }) + $r.ExitCode | Should -Be 1 + $r.Output | Should -Match 'incomplete' + $rows = Import-Csv $script:csv + ($rows | Where-Object DeviceName -eq 'PC-ONE').CollectionError | Should -Match 'Forbidden' + ($rows | Where-Object DeviceName -eq 'PC-TWO').CollectionError | Should -BeNullOrEmpty + } + + It 'pages through the device list (M8)' { + Add-GraphRoute -First -Like '*managedDevices?$skiptoken=2*' -Body (New-GraphPage @((& $script:Dev 'd2' 'PC-TWO'))) + Add-GraphRoute -Like '*/managedDevices' -Body (New-GraphPage @((& $script:Dev 'd1' 'PC-ONE')) -NextLink 'https://graph.microsoft.com/v1.0/deviceManagement/managedDevices?$skiptoken=2') + Add-GraphRoute -Like '*deviceCompliancePolicyStates' -Body (New-GraphPage @()) + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ ExportPath = $script:csv }) + $r.ExitCode | Should -Be 0 + (Import-Csv $script:csv).DeviceName | Should -Be @('PC-ONE', 'PC-TWO') + } + + It 'reads one device with -DeviceId' { + Add-GraphRoute -Like "*managedDevices('11111111-2222-3333-4444-555555555555')" -Body (& $script:Dev '11111111-2222-3333-4444-555555555555' 'PC-ONE') + Add-GraphRoute -Like '*deviceCompliancePolicyStates' -Body (New-GraphPage @()) + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ DeviceId = '11111111-2222-3333-4444-555555555555'; ExportPath = $script:csv }) + $r.ExitCode | Should -Be 0 + @(Import-Csv $script:csv).Count | Should -Be 1 + } + + It 'rejects a DeviceId that is not a GUID without calling Graph' { + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ DeviceId = "x' or 1 eq 1" }) + $r.ExitCode | Should -Be 1 + $global:IntuneTestState.Calls.Count | Should -Be 0 + } + + It 'URL-encodes the UPN filter so a + survives, and keeps the quotes balanced (L4)' { + Add-GraphRoute -Like '*managedDevices?$filter=*' -Body (New-GraphPage @()) + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ UserPrincipalName = 'first+last@example.com' }) + $r.ExitCode | Should -Be 0 + $uri = ($global:IntuneTestState.Calls | Where-Object { $_.Uri -like '*filter=*' }).Uri + # [uri]::ToString() differs between Windows PowerShell 5.1 and 7 in how much it decodes, so accept both forms + $uri | Should -Match "userPrincipalName( |%20)eq( |%20)(%27|')first(%2B|\+)last(%40|@)example\.com(%27|')$" + } + + It '-SkipPolicyStates makes no per-device call' { + Add-GraphRoute -Like '*/managedDevices' -Body (New-GraphPage @((& $script:Dev 'd1' 'PC-ONE'))) + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ SkipPolicyStates = $true; ExportPath = $script:csv }) + $r.ExitCode | Should -Be 0 + ($global:IntuneTestState.Calls | Where-Object { $_.Uri -like '*deviceCompliancePolicyStates*' }).Count | Should -Be 0 + } + + It 'neutralises a device name that starts with = (L3)' { + Add-GraphRoute -Like '*/managedDevices' -Body (New-GraphPage @((& $script:Dev 'd1' '=cmd|calc'))) + Add-GraphRoute -Like '*deviceCompliancePolicyStates' -Body (New-GraphPage @()) + Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ ExportPath = $script:csv }) | Out-Null + (Import-Csv $script:csv).DeviceName | Should -Be "'=cmd|calc" + } + + It 'never installs Microsoft.Graph (M6)' { + Add-GraphRoute -Like '*/managedDevices' -Body (New-GraphPage @()) + (Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments $script:creds).ExitCode | Should -Be 0 + Should -Invoke Install-Module -Times 0 -Exactly + (Get-Content $script:ScriptPath -Raw) | Should -Not -Match 'Install-Module' + } +} diff --git a/Tests/Get-IntuneDeviceDetails.Tests.ps1 b/Tests/Get-IntuneDeviceDetails.Tests.ps1 new file mode 100644 index 0000000..0638eaf --- /dev/null +++ b/Tests/Get-IntuneDeviceDetails.Tests.ps1 @@ -0,0 +1,75 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '5.0.0' } + +# Tests for Reporting/Get-IntuneDeviceDetails.ps1 (audit findings M6, M7, M8, L3, L4). + +. (Join-Path $PSScriptRoot 'TestHelpers.ps1') + +BeforeAll { + . (Join-Path $PSScriptRoot 'TestHelpers.ps1') + $script:ScriptPath = Get-RepoPath 'Reporting\Get-IntuneDeviceDetails.ps1' + Import-Module (Get-ModuleManifestPath) -Force + $script:Dev = { param($Id, $Name) [PSCustomObject]@{ id = $Id; deviceName = $Name; userPrincipalName = 'u@example.test'; complianceState = 'compliant'; osVersion = '10.0' } } +} + +Describe 'Get-IntuneDeviceDetails.ps1' { + BeforeEach { + $global:IntuneTestState = New-GraphTestState + Mock Invoke-RestMethod -ModuleName IntuneCommon -MockWith $script:GraphMockBody + Mock Start-Sleep -ModuleName IntuneCommon { } + Mock Install-Module { throw 'Install-Module must never be called' } + $script:csv = Join-Path $TestDrive 'out.csv' + if (Test-Path $script:csv) { Remove-Item $script:csv } + $script:creds = @{ AppId = 'app-id'; TenantId = 'tenant-id'; ClientSecret = 'plain-secret' } + Remove-Item Env:\INTUNE_APP_ID, Env:\INTUNE_TENANT_ID, Env:\INTUNE_CLIENT_SECRET -ErrorAction SilentlyContinue + } + AfterEach { Remove-Variable -Name IntuneTestState -Scope Global -ErrorAction SilentlyContinue } + + It 'reads every page of a device-name search (M8)' { + Add-GraphRoute -First -Like '*$skiptoken=2*' -Body (New-GraphPage @((& $script:Dev 'd2' 'LAPTOP-02'))) + Add-GraphRoute -Like '*managedDevices?$filter=*' -Body (New-GraphPage @((& $script:Dev 'd1' 'LAPTOP-01')) -NextLink 'https://graph.microsoft.com/v1.0/deviceManagement/managedDevices?$filter=x&$skiptoken=2') + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ DeviceName = 'LAPTOP'; ExportPath = $script:csv }) + $r.ExitCode | Should -Be 0 + (Import-Csv $script:csv).DeviceName | Should -Be @('LAPTOP-01', 'LAPTOP-02') + } + + It 'doubles an apostrophe in a device name instead of deleting it, and URL-encodes the filter (L1)' { + Add-GraphRoute -Like '*managedDevices?$filter=*' -Body (New-GraphPage @()) + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ DeviceName = "O'Brien-PC" }) + $r.ExitCode | Should -Be 0 + $uri = ($global:IntuneTestState.Calls | Where-Object { $_.Uri -like '*filter=*' }).Uri + # contains(deviceName,'O''Brien-PC') URL-encoded: ' is %27, so the doubled quote is %27%27 + $uri | Should -Match "O(%27|')(%27|')Brien-PC" + } + + It 'treats * in a device name as a plain character that is removed, not as a wildcard' { + Add-GraphRoute -Like '*managedDevices?$filter=*' -Body (New-GraphPage @()) + Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ DeviceName = 'LAPTOP-*' }) | Out-Null + $uri = ($global:IntuneTestState.Calls | Where-Object { $_.Uri -like '*filter=*' }).Uri + $uri | Should -Not -Match '%2A' + $uri | Should -Match "LAPTOP-(%27|')" + } + + It 'rejects a DeviceName that is only wildcards without calling Graph' { + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ DeviceName = '***' }) + $r.ExitCode | Should -Be 1 + $global:IntuneTestState.Calls.Count | Should -Be 0 + } + + It 'neutralises a device name that starts with = (L3)' { + Add-GraphRoute -Like '*/managedDevices' -Body (New-GraphPage @((& $script:Dev 'd1' '=1+1'))) + Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ ExportPath = $script:csv }) | Out-Null + (Import-Csv $script:csv).DeviceName | Should -Be "'=1+1" + } + + It 'never installs Microsoft.Graph (M6)' { + Add-GraphRoute -Like '*/managedDevices' -Body (New-GraphPage @()) + (Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments $script:creds).ExitCode | Should -Be 0 + Should -Invoke Install-Module -Times 0 -Exactly + (Get-Content $script:ScriptPath -Raw) | Should -Not -Match 'Install-Module' + } + + It 'exits 1 when Graph returns 403' { + Add-GraphRoute -Like '*/managedDevices' -Throw (New-HttpException -StatusCode 403) + (Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments $script:creds).ExitCode | Should -Be 1 + } +} diff --git a/Tests/Get-IntuneDeviceHealth.Tests.ps1 b/Tests/Get-IntuneDeviceHealth.Tests.ps1 new file mode 100644 index 0000000..7f731ac --- /dev/null +++ b/Tests/Get-IntuneDeviceHealth.Tests.ps1 @@ -0,0 +1,114 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '5.0.0' } + +# Tests for Reporting/Get-IntuneDeviceHealth.ps1 (audit findings M10, M6, M8). + +. (Join-Path $PSScriptRoot 'TestHelpers.ps1') + +BeforeAll { + . (Join-Path $PSScriptRoot 'TestHelpers.ps1') + $script:ScriptPath = Get-RepoPath 'Reporting\Get-IntuneDeviceHealth.ps1' + Import-Module (Get-ModuleManifestPath) -Force + . ([scriptblock]::Create((Import-ScriptFunction -Path $script:ScriptPath -Name 'Get-DeviceHealthAssessment'))) + + $script:Now = [datetime]'2025-06-01T12:00:00Z' + # A device with nothing wrong + function New-HealthyDevice { + [PSCustomObject]@{ + id = 'd1'; deviceName = 'PC-ONE'; userPrincipalName = 'u@example.test' + enrolledDateTime = '2023-01-01T00:00:00Z'; lastSyncDateTime = '2025-06-01T11:00:00Z' + complianceState = 'compliant'; managementAgent = 'mdm'; operatingSystem = 'Windows'; osVersion = '10.0' + totalStorageSpaceInBytes = 500GB; freeStorageSpaceInBytes = 300GB + } + } +} + +Describe 'Get-DeviceHealthAssessment (M10)' { + It 'scores a healthy device 100 with no issues' { + $r = Get-DeviceHealthAssessment -Device (New-HealthyDevice) -Now $script:Now + $r.HealthScore | Should -Be 100 + $r.OverallHealth | Should -Be 'Healthy' + $r.HealthIssueCount | Should -Be 0 + } + + It 'does NOT flag Graph management agent as unsupported' -ForEach @( + @{ Agent = 'mdm' }, @{ Agent = 'eas' }, @{ Agent = 'easMdm' }, @{ Agent = 'intuneClient' }, + @{ Agent = 'configurationManagerClientMdm' }, @{ Agent = 'microsoft365ManagedMdm' }, @{ Agent = 'msSense' } + ) { + $d = New-HealthyDevice; $d.managementAgent = $Agent + $r = Get-DeviceHealthAssessment -Device $d -Now $script:Now + $r.ManagementStatus | Should -Be 'Healthy' + $r.HealthScore | Should -Be 100 + } + + It 'flags an agent of "unknown" and a missing agent' { + $d = New-HealthyDevice; $d.managementAgent = 'unknown' + (Get-DeviceHealthAssessment -Device $d -Now $script:Now).ManagementStatus | Should -Be 'Unknown' + $d.managementAgent = $null + (Get-DeviceHealthAssessment -Device $d -Now $script:Now).HealthIssues | Should -Match 'Management agent missing' + } + + It 'does not penalise a device for being enrolled over a year' { + $d = New-HealthyDevice; $d.enrolledDateTime = '2018-01-01T00:00:00Z' + (Get-DeviceHealthAssessment -Device $d -Now $script:Now).HealthScore | Should -Be 100 + } + + It 'treats Graph''s 0001-01-01 placeholder as Never Synced, not Stale' { + $d = New-HealthyDevice; $d.lastSyncDateTime = '0001-01-01T00:00:00Z' + $r = Get-DeviceHealthAssessment -Device $d -Now $script:Now + $r.SyncStatus | Should -Be 'Never Synced' + $r.HealthIssues | Should -Match 'never synced' + $r.HealthScore | Should -Be 75 + } + + It 'treats a null last sync as Never Synced' { + $d = New-HealthyDevice; $d.lastSyncDateTime = $null + (Get-DeviceHealthAssessment -Device $d -Now $script:Now).SyncStatus | Should -Be 'Never Synced' + } + + It 'marks a sync of hours ago as ' -ForEach @( + @{ Hours = 2; Status = 'Healthy' }, @{ Hours = 10; Status = 'Warning' }, @{ Hours = 30; Status = 'Stale' } + ) { + $d = New-HealthyDevice; $d.lastSyncDateTime = $script:Now.AddHours(-$Hours).ToString('o') + (Get-DeviceHealthAssessment -Device $d -Now $script:Now).SyncStatus | Should -Be $Status + } + + It 'subtracts the documented weights for compliance and storage' { + $d = New-HealthyDevice; $d.complianceState = 'nonCompliant'; $d.freeStorageSpaceInBytes = 20GB + $r = Get-DeviceHealthAssessment -Device $d -Now $script:Now + $r.HealthScore | Should -Be (100 - 15 - 15) + $r.OverallHealth | Should -Be 'Fair' + } +} + +Describe 'Get-IntuneDeviceHealth.ps1' { + BeforeEach { + $global:IntuneTestState = New-GraphTestState + Mock Invoke-RestMethod -ModuleName IntuneCommon -MockWith $script:GraphMockBody + Mock Start-Sleep -ModuleName IntuneCommon { } + Mock Install-Module { throw 'Install-Module must never be called' } + $script:csv = Join-Path $TestDrive 'out.csv' + if (Test-Path $script:csv) { Remove-Item $script:csv } + $script:creds = @{ AppId = 'app-id'; TenantId = 'tenant-id'; ClientSecret = 'plain-secret' } + Remove-Item Env:\INTUNE_APP_ID, Env:\INTUNE_TENANT_ID, Env:\INTUNE_CLIENT_SECRET -ErrorAction SilentlyContinue + } + AfterEach { Remove-Variable -Name IntuneTestState -Scope Global -ErrorAction SilentlyContinue } + + It 'reads every page and exports one row per device (M8)' { + $recent = (Get-Date).AddMinutes(-5).ToString('o') + $mk = { param($id, $name) [PSCustomObject]@{ id = $id; deviceName = $name; enrolledDateTime = '2023-01-01T00:00:00Z'; lastSyncDateTime = $recent; complianceState = 'compliant'; managementAgent = 'configurationManagerClientMdm'; operatingSystem = 'Windows' } } + Add-GraphRoute -First -Like '*$skiptoken=2*' -Body (New-GraphPage @((& $mk 'd2' 'PC-TWO'))) + Add-GraphRoute -Like '*/managedDevices' -Body (New-GraphPage @((& $mk 'd1' 'PC-ONE')) -NextLink 'https://graph.microsoft.com/v1.0/deviceManagement/managedDevices?$skiptoken=2') + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ ExportPath = $script:csv }) + $r.ExitCode | Should -Be 0 + $rows = Import-Csv $script:csv + $rows.DeviceName | Should -Be @('PC-ONE', 'PC-TWO') + $rows.OverallHealth | Should -Be @('Healthy', 'Healthy') + } + + It 'never installs Microsoft.Graph (M6)' { + Add-GraphRoute -Like '*/managedDevices' -Body (New-GraphPage @()) + (Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments $script:creds).ExitCode | Should -Be 0 + Should -Invoke Install-Module -Times 0 -Exactly + (Get-Content $script:ScriptPath -Raw) | Should -Not -Match 'Install-Module' + } +} diff --git a/Tests/Get-IntuneDeviceLogs.Tests.ps1 b/Tests/Get-IntuneDeviceLogs.Tests.ps1 new file mode 100644 index 0000000..6a1b9d8 --- /dev/null +++ b/Tests/Get-IntuneDeviceLogs.Tests.ps1 @@ -0,0 +1,97 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '5.0.0' } + +# Tests for Troubleshooting/Get-IntuneDeviceLogs.ps1 (audit finding M11). +# File copies, reg.exe, wevtutil.exe and icacls.exe are mocked, so nothing is exported or changed. + +. (Join-Path $PSScriptRoot 'TestHelpers.ps1') +$script:Elevated = Test-IsElevated + +BeforeAll { + . (Join-Path $PSScriptRoot 'TestHelpers.ps1') + $script:ScriptPath = Get-RepoPath 'Troubleshooting\Get-IntuneDeviceLogs.ps1' +} + +Describe 'Get-IntuneDeviceLogs.ps1' -Skip:(-not $script:Elevated) { + BeforeEach { + foreach ($c in ($script:StateChangingCommands + @('reg', 'wevtutil', 'icacls'))) { Mock -CommandName $c -MockWith ([scriptblock]::Create("throw 'UNMOCKED state-changing call: $c'")) } + + $global:IntuneTestState = @{ + OutputPath = (Join-Path $TestDrive 'out') + HasIme = $true + HasMdm = $true + RegExit = 0 + EvtExit = 0 + Present = @('Microsoft-Windows-DeviceManagement-Enterprise-Diagnostics-Provider/Admin') + Asked = @() + } + + Mock Test-Path { + $p = "$Path" + if ($p -eq $global:IntuneTestState.OutputPath) { return $false } + if ($p -like '*IntuneManagementExtension*') { return $global:IntuneTestState.HasIme } + if ($p -like '*DeviceManagement*Logs*') { return $global:IntuneTestState.HasMdm } + return $true + } + Mock New-Item { [PSCustomObject]@{ FullName = "$Path" } } + Mock Get-ChildItem { @() } + Mock Copy-Item { } + Mock Out-File { } + Mock Get-CimInstance { [PSCustomObject]@{ Version = '10.0.1'; BuildNumber = '1' } } + Mock icacls { $global:LASTEXITCODE = 0 } + Mock reg { $global:LASTEXITCODE = $global:IntuneTestState.RegExit } + Mock wevtutil { $global:LASTEXITCODE = $global:IntuneTestState.EvtExit } + Mock Get-WinEvent { + $global:IntuneTestState.Asked += "$ListLog" + if ($global:IntuneTestState.Present -contains "$ListLog") { [PSCustomObject]@{ LogName = "$ListLog" } } + } + } + AfterEach { Remove-Variable -Name IntuneTestState -Scope Global -ErrorAction SilentlyContinue } + + It 'exits 0 when everything collected, and restricts the new output folder to SYSTEM and Administrators' { + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments @{ OutputPath = $global:IntuneTestState.OutputPath } + $r.ExitCode | Should -Be 0 + Should -Invoke icacls -Times 1 -Exactly + Should -Invoke Copy-Item -Times 2 -Exactly + } + + It 'exits 1 when the registry export fails, instead of "completed successfully" (M11)' { + $global:IntuneTestState.RegExit = 1 + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments @{ OutputPath = $global:IntuneTestState.OutputPath } + $r.ExitCode | Should -Be 1 + $r.Output | Should -Not -Match 'completed successfully' + } + + It 'exits 1 when a copy fails (M11)' { + Mock Copy-Item { throw 'sharing violation' } + (Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments @{ OutputPath = $global:IntuneTestState.OutputPath }).ExitCode | Should -Be 1 + } + + It 'exits 1 when there is nothing to collect (M11)' { + $global:IntuneTestState.HasIme = $false + $global:IntuneTestState.HasMdm = $false + Mock Test-Path { $p = "$Path"; if ($p -like '*Enrollments*' -or $p -eq $global:IntuneTestState.OutputPath -or $p -like '*Logs' -or $p -like '*Logs*') { return $false }; $true } + (Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments @{ OutputPath = $global:IntuneTestState.OutputPath }).ExitCode | Should -Be 1 + } + + It 'asks only for real event log names, never the bare provider name (M11)' { + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments @{ OutputPath = $global:IntuneTestState.OutputPath; IncludeEventLogs = $true } + $r.ExitCode | Should -Be 0 + $global:IntuneTestState.Asked | Should -Not -Contain 'Microsoft-Windows-DeviceManagement-Enterprise-Diagnostics-Provider' + $global:IntuneTestState.Asked | Should -Contain 'Microsoft-Windows-DeviceManagement-Enterprise-Diagnostics-Provider/Admin' + Should -Invoke wevtutil -Times 1 -Exactly + } + + It 'does not claim event logs were collected when none exist (M11)' { + $global:IntuneTestState.Present = @() + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments @{ OutputPath = $global:IntuneTestState.OutputPath; IncludeEventLogs = $true } + $r.Output | Should -Not -Match 'Collected: .*Windows Event Logs' + $r.Output | Should -Match 'No Windows Event Logs were exported' + Should -Invoke wevtutil -Times 0 -Exactly + } + + It 'exits 1 when wevtutil fails on a log that exists (M11)' { + $global:IntuneTestState.EvtExit = 5 + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments @{ OutputPath = $global:IntuneTestState.OutputPath; IncludeEventLogs = $true } + $r.ExitCode | Should -Be 1 + } +} diff --git a/Tests/Get-IntunePolicyAssignments.Tests.ps1 b/Tests/Get-IntunePolicyAssignments.Tests.ps1 new file mode 100644 index 0000000..d170886 --- /dev/null +++ b/Tests/Get-IntunePolicyAssignments.Tests.ps1 @@ -0,0 +1,128 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '5.0.0' } + +# Tests for Reporting/Get-IntunePolicyAssignments.ps1 (audit findings H5, M6, M7, M8, L3). +# Every Graph and token call goes through a mocked Invoke-RestMethod inside the IntuneCommon module. +# Nothing contacts a tenant. A URI with no route throws. + +. (Join-Path $PSScriptRoot 'TestHelpers.ps1') + +BeforeAll { + . (Join-Path $PSScriptRoot 'TestHelpers.ps1') + $script:ScriptPath = Get-RepoPath 'Reporting\Get-IntunePolicyAssignments.ps1' + Import-Module (Get-ModuleManifestPath) -Force + $script:Base = 'https://graph.microsoft.com/v1.0' +} + +Describe 'Get-IntunePolicyAssignments.ps1' { + BeforeEach { + $global:IntuneTestState = New-GraphTestState + Mock Invoke-RestMethod -ModuleName IntuneCommon -MockWith $script:GraphMockBody + Mock Start-Sleep -ModuleName IntuneCommon { } + Mock Install-Module { throw 'Install-Module must never be called' } + Mock Import-Module -ParameterFilter { "$Name" -like '*Microsoft.Graph*' } { throw 'Microsoft.Graph must not be imported' } + $script:csv = Join-Path $TestDrive 'out.csv' + if (Test-Path $script:csv) { Remove-Item $script:csv } + $script:creds = @{ AppId = 'app-id'; TenantId = 'tenant-id'; ClientSecret = 'plain-secret' } + Remove-Item Env:\INTUNE_APP_ID, Env:\INTUNE_TENANT_ID, Env:\INTUNE_CLIENT_SECRET -ErrorAction SilentlyContinue + } + AfterEach { Remove-Variable -Name IntuneTestState -Scope Global -ErrorAction SilentlyContinue } + + It 'lists a policy that has no assignments instead of dropping it (H5)' { + Add-GraphRoute -Like '*deviceConfigurations' -Body (New-GraphPage @([PSCustomObject]@{ id = 'c1'; displayName = 'Assigned profile' }, [PSCustomObject]@{ id = 'c2'; displayName = 'Orphan profile' })) + Add-GraphRoute -Like "*deviceConfigurations('c1')/assignments" -Body (New-GraphPage @([PSCustomObject]@{ id = 'a1'; intent = 'apply'; target = [PSCustomObject]@{ '@odata.type' = '#microsoft.graph.groupAssignmentTarget'; groupId = 'g1' } })) + Add-GraphRoute -Like "*deviceConfigurations('c2')/assignments" -Body ([PSCustomObject]@{ value = @() }) + Add-GraphRoute -Like '*/groups/g1' -Body ([PSCustomObject]@{ displayName = 'Pilot group' }) + + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ PolicyType = 'Configuration'; ExportPath = $script:csv }) + $r.ExitCode | Should -Be 0 + $rows = Import-Csv $script:csv + $rows.Count | Should -Be 2 + ($rows | Where-Object PolicyName -eq 'Orphan profile').TargetName | Should -Be 'No assignments' + ($rows | Where-Object PolicyName -eq 'Orphan profile').TargetType | Should -Be 'None' + ($rows | Where-Object PolicyName -eq 'Assigned profile').TargetName | Should -Be 'Pilot group' + } + + It 'lists an unassigned COMPLIANCE policy too (the same pattern was in the compliance half)' { + Add-GraphRoute -Like '*deviceCompliancePolicies' -Body (New-GraphPage @([PSCustomObject]@{ id = 'p1'; displayName = 'Orphan compliance' })) + Add-GraphRoute -Like "*deviceCompliancePolicies('p1')/assignments" -Body ([PSCustomObject]@{ value = @() }) + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ PolicyType = 'Compliance'; ExportPath = $script:csv }) + $r.ExitCode | Should -Be 0 + (Import-Csv $script:csv).TargetName | Should -Be 'No assignments' + } + + It 'marks a policy whose assignments call failed as an Error row and exits 1' { + Add-GraphRoute -Like '*deviceConfigurations' -Body (New-GraphPage @([PSCustomObject]@{ id = 'c1'; displayName = 'Denied profile' })) + Add-GraphRoute -Like "*deviceConfigurations('c1')/assignments" -Throw (New-HttpException -StatusCode 403 -Message 'Forbidden') + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ PolicyType = 'Configuration'; ExportPath = $script:csv }) + $r.ExitCode | Should -Be 1 + $r.Output | Should -Match 'incomplete' + $row = Import-Csv $script:csv + $row.TargetType | Should -Be 'Error' + $row.TargetName | Should -Match 'Forbidden' + } + + It 'follows @odata.nextLink for the policy list and for the assignments (M8)' { + Add-GraphRoute -First -Like '*deviceConfigurations?$skiptoken=2*' -Body (New-GraphPage @([PSCustomObject]@{ id = 'c2'; displayName = 'Page two' })) + Add-GraphRoute -Like '*deviceConfigurations' -Body (New-GraphPage @([PSCustomObject]@{ id = 'c1'; displayName = 'Page one' }) -NextLink "$($script:Base)/deviceManagement/deviceConfigurations?`$skiptoken=2") + Add-GraphRoute -First -Like "*deviceConfigurations('c1')/assignments?`$skiptoken=a2*" -Body (New-GraphPage @([PSCustomObject]@{ id = 'a2'; intent = 'apply'; target = [PSCustomObject]@{ '@odata.type' = '#microsoft.graph.allDevicesAssignmentTarget' } })) + Add-GraphRoute -Like "*deviceConfigurations('c1')/assignments" -Body (New-GraphPage @([PSCustomObject]@{ id = 'a1'; intent = 'apply'; target = [PSCustomObject]@{ '@odata.type' = '#microsoft.graph.allLicensedUsersAssignmentTarget' } }) -NextLink "$($script:Base)/deviceManagement/deviceConfigurations('c1')/assignments?`$skiptoken=a2") + Add-GraphRoute -Like "*deviceConfigurations('c2')/assignments" -Body ([PSCustomObject]@{ value = @() }) + + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ PolicyType = 'Configuration'; ExportPath = $script:csv }) + $r.ExitCode | Should -Be 0 + $rows = Import-Csv $script:csv + ($rows | Where-Object PolicyName -eq 'Page two').TargetName | Should -Be 'No assignments' + @($rows | Where-Object PolicyName -eq 'Page one').Count | Should -Be 2 + } + + It 'keeps exclusion targets visible as their own target type' { + Add-GraphRoute -Like '*deviceConfigurations' -Body (New-GraphPage @([PSCustomObject]@{ id = 'c1'; displayName = 'P' })) + Add-GraphRoute -Like "*deviceConfigurations('c1')/assignments" -Body (New-GraphPage @([PSCustomObject]@{ id = 'a1'; target = [PSCustomObject]@{ '@odata.type' = '#microsoft.graph.exclusionGroupAssignmentTarget'; groupId = 'g9' } })) + Add-GraphRoute -Like '*/groups/g9' -Body ([PSCustomObject]@{ displayName = 'Excluded group' }) + Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ PolicyType = 'Configuration'; ExportPath = $script:csv }) | Out-Null + (Import-Csv $script:csv).TargetType | Should -Be '#microsoft.graph.exclusionGroupAssignmentTarget' + } + + It 'neutralises a policy name that starts with = so a spreadsheet will not run it (L3)' { + Add-GraphRoute -Like '*deviceConfigurations' -Body (New-GraphPage @([PSCustomObject]@{ id = 'c1'; displayName = '=HYPERLINK("http://example.invalid","x")' })) + Add-GraphRoute -Like "*deviceConfigurations('c1')/assignments" -Body ([PSCustomObject]@{ value = @() }) + Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ PolicyType = 'Configuration'; ExportPath = $script:csv }) | Out-Null + (Import-Csv $script:csv).PolicyName | Should -BeLike "'=HYPERLINK*" + } + + It 'never installs or imports the Microsoft.Graph meta-module (M6)' { + Add-GraphRoute -Like '*deviceConfigurations' -Body (New-GraphPage @()) + Add-GraphRoute -Like '*deviceCompliancePolicies' -Body (New-GraphPage @()) + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments $script:creds + $r.ExitCode | Should -Be 0 + Should -Invoke Install-Module -Times 0 -Exactly + (Get-Content $script:ScriptPath -Raw) | Should -Not -Match 'Install-Module' + } + + It 'accepts the secret as a SecureString and sends the plain value only to the token endpoint (M7)' { + Add-GraphRoute -Like '*deviceConfigurations' -Body (New-GraphPage @()) + $secure = ConvertTo-SecureString 'secure-secret-value' -AsPlainText -Force + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments @{ AppId = 'app-id'; TenantId = 'tenant-id'; ClientSecretSecure = $secure; PolicyType = 'Configuration' } + $r.ExitCode | Should -Be 0 + $token = $global:IntuneTestState.Calls | Where-Object { $_.Uri -like '*oauth2/v2.0/token' } + @($token).Count | Should -Be 1 + $token.Body.client_secret | Should -Be 'secure-secret-value' + $r.Output | Should -Not -Match 'secure-secret-value' + } + + It 'reads credentials from INTUNE_* environment variables (M7)' { + $env:INTUNE_APP_ID = 'env-app'; $env:INTUNE_TENANT_ID = 'env-tenant'; $env:INTUNE_CLIENT_SECRET = 'env-secret' + try { + Add-GraphRoute -Like '*deviceConfigurations' -Body (New-GraphPage @()) + (Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments @{ PolicyType = 'Configuration' }).ExitCode | Should -Be 0 + ($global:IntuneTestState.Calls | Where-Object { $_.Uri -like '*env-tenant*' }) | Should -Not -BeNullOrEmpty + } + finally { Remove-Item Env:\INTUNE_APP_ID, Env:\INTUNE_TENANT_ID, Env:\INTUNE_CLIENT_SECRET -ErrorAction SilentlyContinue } + } + + It 'exits 1 without any HTTP call when credentials are missing or placeholders' { + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments @{ AppId = ''; TenantId = 't'; ClientSecret = 's' } + $r.ExitCode | Should -Be 1 + $global:IntuneTestState.Calls.Count | Should -Be 0 + } +} diff --git a/Tests/Get-IntuneWin32AppDetails.Tests.ps1 b/Tests/Get-IntuneWin32AppDetails.Tests.ps1 new file mode 100644 index 0000000..a84c785 --- /dev/null +++ b/Tests/Get-IntuneWin32AppDetails.Tests.ps1 @@ -0,0 +1,118 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '5.0.0' } + +# Tests for Reporting/Get-IntuneWin32AppDetails.ps1 (audit findings H5, M9, M6, M8, L3). + +. (Join-Path $PSScriptRoot 'TestHelpers.ps1') + +BeforeAll { + . (Join-Path $PSScriptRoot 'TestHelpers.ps1') + $script:ScriptPath = Get-RepoPath 'Reporting\Get-IntuneWin32AppDetails.ps1' + Import-Module (Get-ModuleManifestPath) -Force + $script:App = { param($Id, $Name) [PSCustomObject]@{ id = $Id; displayName = $Name; '@odata.type' = '#microsoft.graph.win32LobApp'; displayVersion = '1.2.3'; publisher = 'Contoso' } } + $script:Dev = '11111111-2222-3333-4444-555555555555' +} + +Describe 'Get-IntuneWin32AppDetails.ps1' { + BeforeEach { + $global:IntuneTestState = New-GraphTestState + Mock Invoke-RestMethod -ModuleName IntuneCommon -MockWith $script:GraphMockBody + Mock Start-Sleep -ModuleName IntuneCommon { } + Mock Install-Module { throw 'Install-Module must never be called' } + $script:csv = Join-Path $TestDrive 'out.csv' + if (Test-Path $script:csv) { Remove-Item $script:csv } + $script:creds = @{ AppId = 'app-id'; TenantId = 'tenant-id'; ClientSecret = 'plain-secret' } + Remove-Item Env:\INTUNE_APP_ID, Env:\INTUNE_TENANT_ID, Env:\INTUNE_CLIENT_SECRET -ErrorAction SilentlyContinue + } + AfterEach { Remove-Variable -Name IntuneTestState -Scope Global -ErrorAction SilentlyContinue } + + It 'shows an assignments failure as an error, NOT as 0 assignments, and exits 1 (H5)' { + Add-GraphRoute -Like '*mobileApps?$filter=*' -Body (New-GraphPage @((& $script:App 'a1' 'App One'), (& $script:App 'a2' 'App Two'))) + Add-GraphRoute -Like "*mobileApps('a1')/assignments" -Throw (New-HttpException -StatusCode 403 -Message 'Forbidden') + Add-GraphRoute -Like "*mobileApps('a2')/assignments" -Body (New-GraphPage @([PSCustomObject]@{ id = 'x'; target = [PSCustomObject]@{ '@odata.type' = '#microsoft.graph.allDevicesAssignmentTarget' } })) + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ ExportPath = $script:csv }) + $r.ExitCode | Should -Be 1 + $r.Output | Should -Match 'incomplete' + $rows = Import-Csv $script:csv + $one = $rows | Where-Object AppName -eq 'App One' + $one.AssignmentError | Should -Match 'Forbidden' + $one.AssignmentCount | Should -BeNullOrEmpty + ($rows | Where-Object AppName -eq 'App Two').AssignmentCount | Should -Be '1' + } + + It 'a real zero-assignment app reports 0 with no error' { + Add-GraphRoute -Like '*mobileApps?$filter=*' -Body (New-GraphPage @((& $script:App 'a1' 'App One'))) + Add-GraphRoute -Like "*mobileApps('a1')/assignments" -Body ([PSCustomObject]@{ value = @() }) + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ ExportPath = $script:csv }) + $r.ExitCode | Should -Be 0 + $row = Import-Csv $script:csv + $row.AssignmentCount | Should -Be '0' + $row.AssignmentError | Should -BeNullOrEmpty + } + + It 'reports the install state Intune holds for the device, matched on deviceId (M9)' { + Add-GraphRoute -Like '*mobileApps?$filter=*' -Body (New-GraphPage @((& $script:App 'a1' '7-Zip'), (& $script:App 'a2' 'Other App'), (& $script:App 'a3' 'Broken App'))) + Add-GraphRoute -Like '*/assignments' -Body (New-GraphPage @()) + Add-GraphRoute -Like "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps('a1')/deviceStatuses" -Body (New-GraphPage @( + [PSCustomObject]@{ deviceId = 'someone-else'; installState = 'failed' }, + [PSCustomObject]@{ deviceId = $script:Dev; installState = 'installed'; displayVersion = '24.08' })) + Add-GraphRoute -Like "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps('a2')/deviceStatuses" -Body (New-GraphPage @([PSCustomObject]@{ deviceId = 'someone-else'; installState = 'installed' })) + Add-GraphRoute -Like "https://graph.microsoft.com/beta/deviceAppManagement/mobileApps('a3')/deviceStatuses" -Body (New-GraphPage @([PSCustomObject]@{ deviceId = $script:Dev; installState = 'failed' })) + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ DeviceId = $script:Dev; ExportPath = $script:csv }) + $r.ExitCode | Should -Be 0 + $rows = Import-Csv $script:csv + ($rows | Where-Object AppName -eq '7-Zip').DeviceInstallStatus | Should -Be 'installed' + ($rows | Where-Object AppName -eq '7-Zip').DeviceInstallVersion | Should -Be '24.08' + ($rows | Where-Object AppName -eq 'Other App').DeviceInstallStatus | Should -Be 'NotReported' + ($rows | Where-Object AppName -eq 'Broken App').DeviceInstallStatus | Should -Be 'failed' + # The old name match against software inventory must be gone + ($global:IntuneTestState.Calls | Where-Object { $_.Uri -like '*detectedApps*' }).Count | Should -Be 0 + } + + It 'marks the device state Unknown with an error and exits 1 when the status call fails' { + Add-GraphRoute -Like '*mobileApps?$filter=*' -Body (New-GraphPage @((& $script:App 'a1' 'App One'))) + Add-GraphRoute -Like '*/assignments' -Body (New-GraphPage @()) + Add-GraphRoute -Like 'https://graph.microsoft.com/beta/*deviceStatuses' -Throw (New-HttpException -StatusCode 403 -Message 'Forbidden') + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ DeviceId = $script:Dev; ExportPath = $script:csv }) + $r.ExitCode | Should -Be 1 + $row = Import-Csv $script:csv + $row.DeviceInstallStatus | Should -Be 'Unknown' + $row.DeviceStatusError | Should -Match 'Forbidden' + } + + It 'exits 1, not "completed successfully", when the single-app fetch fails (M9)' { + Add-GraphRoute -Like "*mobileApps('11111111-aaaa-bbbb-cccc-111111111111')" -Throw (New-HttpException -StatusCode 404 -Message 'Not Found') + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ IntuneAppId = '11111111-aaaa-bbbb-cccc-111111111111' }) + $r.ExitCode | Should -Be 1 + $r.Output | Should -Not -Match 'completed successfully' + } + + It 'warns and exits 0 for an app that is not a Win32 app' { + Add-GraphRoute -Like "*mobileApps('11111111-aaaa-bbbb-cccc-111111111111')" -Body ([PSCustomObject]@{ id = 'x'; displayName = 'Web'; '@odata.type' = '#microsoft.graph.webApp' }) + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ IntuneAppId = '11111111-aaaa-bbbb-cccc-111111111111' }) + $r.ExitCode | Should -Be 0 + $r.Output | Should -Match 'not a Win32 app' + } + + It 'pages through the app list (M8)' { + Add-GraphRoute -First -Like '*$skiptoken=2*' -Body (New-GraphPage @((& $script:App 'a2' 'App Two'))) + Add-GraphRoute -Like '*mobileApps?$filter=*' -Body (New-GraphPage @((& $script:App 'a1' 'App One')) -NextLink 'https://graph.microsoft.com/v1.0/deviceAppManagement/mobileApps?$filter=x&$skiptoken=2') + Add-GraphRoute -Like '*/assignments' -Body (New-GraphPage @()) + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ ExportPath = $script:csv }) + $r.ExitCode | Should -Be 0 + (Import-Csv $script:csv).AppName | Should -Be @('App One', 'App Two') + } + + It 'neutralises an app name that starts with = (L3)' { + Add-GraphRoute -Like '*mobileApps?$filter=*' -Body (New-GraphPage @((& $script:App 'a1' '=cmd()'))) + Add-GraphRoute -Like '*/assignments' -Body (New-GraphPage @()) + Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments ($script:creds + @{ ExportPath = $script:csv }) | Out-Null + (Import-Csv $script:csv).AppName | Should -Be "'=cmd()" + } + + It 'never installs Microsoft.Graph (M6)' { + Add-GraphRoute -Like '*mobileApps?$filter=*' -Body (New-GraphPage @()) + (Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments $script:creds).ExitCode | Should -Be 0 + Should -Invoke Install-Module -Times 0 -Exactly + (Get-Content $script:ScriptPath -Raw) | Should -Not -Match 'Install-Module' + } +} diff --git a/Tests/IntuneCommon.Tests.ps1 b/Tests/IntuneCommon.Tests.ps1 new file mode 100644 index 0000000..ce63a55 --- /dev/null +++ b/Tests/IntuneCommon.Tests.ps1 @@ -0,0 +1,165 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '5.0.0' } + +# Tests for Common/IntuneCommon.psm1 and its manifest (audit findings L1, L3, L4, M7, M8). + +. (Join-Path $PSScriptRoot 'TestHelpers.ps1') + +BeforeAll { + . (Join-Path $PSScriptRoot 'TestHelpers.ps1') + Import-Module (Get-ModuleManifestPath) -Force +} + +Describe 'IntuneCommon manifest (L1)' { + It 'is a valid manifest that exports every function the module defines' { + $manifest = Test-ModuleManifest -Path (Get-ModuleManifestPath) + $manifest.Version.ToString() | Should -Be '1.1.0' + $manifest.Author | Should -Be 'NullSpace-BitCradle' + $defined = (Get-Module IntuneCommon).ExportedFunctions.Keys | Sort-Object + $manifest.ExportedFunctions.Keys | Sort-Object | Should -Be $defined + } +} + +Describe 'Get-IntuneCredential (M7)' { + BeforeEach { Remove-Item Env:\INTUNE_APP_ID, Env:\INTUNE_TENANT_ID, Env:\INTUNE_CLIENT_SECRET -ErrorAction SilentlyContinue } + AfterEach { Remove-Item Env:\INTUNE_APP_ID, Env:\INTUNE_TENANT_ID, Env:\INTUNE_CLIENT_SECRET -ErrorAction SilentlyContinue } + + It 'returns the secret as a SecureString' { + $c = Get-IntuneCredential -AppId 'a' -TenantId 't' -ClientSecret 's' + $c.ClientSecret | Should -BeOfType [securestring] + [System.Net.NetworkCredential]::new('', $c.ClientSecret).Password | Should -Be 's' + } + It 'prefers a SecureString secret over a plain one' { + $c = Get-IntuneCredential -AppId 'a' -TenantId 't' -ClientSecret 'plain' -ClientSecretSecure (ConvertTo-SecureString 'secure' -AsPlainText -Force) + [System.Net.NetworkCredential]::new('', $c.ClientSecret).Password | Should -Be 'secure' + } + It 'falls back to the INTUNE_* environment variables' { + $env:INTUNE_APP_ID = 'ea'; $env:INTUNE_TENANT_ID = 'et'; $env:INTUNE_CLIENT_SECRET = 'es' + $c = Get-IntuneCredential + $c.AppId | Should -Be 'ea' + $c.TenantId | Should -Be 'et' + } + It 'prefers parameters over environment variables' { + $env:INTUNE_APP_ID = 'ea'; $env:INTUNE_TENANT_ID = 'et'; $env:INTUNE_CLIENT_SECRET = 'es' + (Get-IntuneCredential -AppId 'pa' -TenantId 'pt' -ClientSecret 'ps').AppId | Should -Be 'pa' + } + It 'rejects ' -ForEach @( + @{ Name = 'a missing tenant'; Params = @{ AppId = 'a'; ClientSecret = 's' } }, + @{ Name = 'a missing secret'; Params = @{ AppId = 'a'; TenantId = 't' } }, + @{ Name = 'a placeholder app id'; Params = @{ AppId = ''; TenantId = 't'; ClientSecret = 's' } }, + @{ Name = 'a placeholder secret'; Params = @{ AppId = 'a'; TenantId = 't'; ClientSecret = '' } } + ) { + { Get-IntuneCredential @Params } | Should -Throw '*valid credentials*' + } +} + +Describe 'OData escaping (L1, L4)' { + It 'doubles an apostrophe instead of deleting it' { + ConvertTo-ODataStringLiteral -Value "O'Brien-PC" | Should -Be "'O''Brien-PC'" + Remove-ODataInjectionChars -InputString "O'Brien" | Should -Be "O''Brien" + } + It 'keeps a semicolon, which is not special inside a quoted literal' { + ConvertTo-ODataStringLiteral -Value 'a;b' | Should -Be "'a;b'" + } + It 'cannot be broken out of with a quote' { + ConvertTo-ODataStringLiteral -Value "x' or 1 eq 1 or name eq 'y" | Should -Be "'x'' or 1 eq 1 or name eq ''y'" + } + It 'Test-ODataFilterInput strips wildcard characters unless allowed, and escapes quotes' { + Test-ODataFilterInput -InputString "LAP*'TOP" | Should -Be "LAP''TOP" + Test-ODataFilterInput -InputString "LAP*TOP" -AllowWildcards | Should -Be 'LAP*TOP' + { Test-ODataFilterInput -InputString '***' } | Should -Throw '*empty*' + } + It 'a UPN with + survives once the filter is URL-encoded (L4)' { + $filter = "userPrincipalName eq $(ConvertTo-ODataStringLiteral -Value 'first+last@example.com')" + [uri]::EscapeDataString($filter) | Should -Match 'first%2Blast%40example\.com' + } +} + +Describe 'CSV formula safety (L3)' { + It 'prefixes a value that starts with ' -ForEach @( + @{ Value = '=SUM(A1)' }, @{ Value = '+1' }, @{ Value = '-1+1' }, @{ Value = '@cmd' } + ) { + Protect-CsvValue -Value $Value | Should -Be ("'" + $Value) + } + It 'leaves ordinary values, empty strings and nulls alone' { + Protect-CsvValue -Value 'LAPTOP-01' | Should -Be 'LAPTOP-01' + Protect-CsvValue -Value '' | Should -Be '' + Protect-CsvValue -Value $null | Should -BeNullOrEmpty + } + It 'ConvertTo-SafeCsvRecord keeps column order and non-string values' { + $row = [PSCustomObject][ordered]@{ Name = '=evil()'; Count = 5; When = [datetime]'2025-01-02'; Empty = $null } + $out = $row | ConvertTo-SafeCsvRecord + $out.PSObject.Properties.Name | Should -Be @('Name', 'Count', 'When', 'Empty') + $out.Name | Should -Be "'=evil()" + $out.Count | Should -Be 5 + $out.When | Should -BeOfType [datetime] + } +} + +Describe 'Get-GraphAccessToken (M7)' { + BeforeEach { + $global:IntuneTestState = New-GraphTestState + Mock Invoke-RestMethod -ModuleName IntuneCommon -MockWith $script:GraphMockBody + } + AfterEach { Remove-Variable -Name IntuneTestState -Scope Global -ErrorAction SilentlyContinue } + + It 'sends a SecureString secret as client_secret' { + $t = Get-GraphAccessToken -AppId 'a' -TenantId 't' -ClientSecretSecure (ConvertTo-SecureString 'hidden' -AsPlainText -Force) + $t | Should -Be 'test-token' + $global:IntuneTestState.Calls[0].Body.client_secret | Should -Be 'hidden' + $global:IntuneTestState.Calls[0].Uri | Should -Match '/t/oauth2/v2\.0/token$' + } + It 'still accepts a plain-string secret' { + Get-GraphAccessToken -AppId 'a' -TenantId 't' -ClientSecret 'plain' | Should -Be 'test-token' + } +} + +Describe 'Invoke-GraphApiWithRetry and Get-GraphApiAllPages (M8)' { + BeforeEach { + $global:IntuneTestState = New-GraphTestState + $global:IntuneTestState.Sleeps = @() + Mock Invoke-RestMethod -ModuleName IntuneCommon -MockWith $script:GraphMockBody + Mock Start-Sleep -ModuleName IntuneCommon { $global:IntuneTestState.Sleeps += $Seconds } + } + AfterEach { Remove-Variable -Name IntuneTestState -Scope Global -ErrorAction SilentlyContinue } + + It 'retries a 429 using Retry-After, then returns the result' { + $ex = New-HttpException -StatusCode 429 + $ex.Response.Headers = @{ 'Retry-After' = '7' } + $global:IntuneTestState.Attempts = 0 + Mock Invoke-RestMethod -ModuleName IntuneCommon { + $global:IntuneTestState.Attempts++ + if ($global:IntuneTestState.Attempts -eq 1) { throw $global:IntuneTestState.Ex } + [PSCustomObject]@{ ok = $true } + } + $global:IntuneTestState.Ex = $ex + $r = Invoke-GraphApiWithRetry -Uri 'https://graph.microsoft.com/v1.0/x' -Headers @{} + $r.ok | Should -BeTrue + $global:IntuneTestState.Sleeps | Should -Be @(7) + } + + It 'does not retry a 403' { + Add-GraphRoute -Like '*/x' -Throw (New-HttpException -StatusCode 403) + { Invoke-GraphApiWithRetry -Uri 'https://graph.microsoft.com/v1.0/x' -Headers @{} } | Should -Throw + @($global:IntuneTestState.Calls | Where-Object { $_.Uri -like '*/x' }).Count | Should -Be 1 + } + + It 'Get-GraphApiAllPages follows every nextLink and returns every item' { + Add-GraphRoute -First -Like '*/list?page=3' -Body (New-GraphPage @(5)) + Add-GraphRoute -First -Like '*/list?page=2' -Body (New-GraphPage @(3, 4) -NextLink 'https://graph.microsoft.com/v1.0/list?page=3') + Add-GraphRoute -Like '*/list' -Body (New-GraphPage @(1, 2) -NextLink 'https://graph.microsoft.com/v1.0/list?page=2') + @(Get-GraphApiAllPages -Uri 'https://graph.microsoft.com/v1.0/list' -Headers @{}) | Should -Be @(1, 2, 3, 4, 5) + } + + It 'Get-GraphApiAllPages returns an empty list for an empty value array' { + Add-GraphRoute -Like '*/empty' -Body ([PSCustomObject]@{ value = @() }) + @(Get-GraphApiAllPages -Uri 'https://graph.microsoft.com/v1.0/empty' -Headers @{}).Count | Should -Be 0 + } +} + +Describe 'The H5 premise: an empty Graph list is not $null' { + It 'parses {"value":[]} to an empty array, so a $null test never sees it' { + $r = '{"value":[]}' | ConvertFrom-Json + ($null -eq $r.value) | Should -BeFalse + @($r.value).Count | Should -Be 0 + } +} diff --git a/Tests/PrintSpoolerService.Tests.ps1 b/Tests/PrintSpoolerService.Tests.ps1 new file mode 100644 index 0000000..489e3b2 --- /dev/null +++ b/Tests/PrintSpoolerService.Tests.ps1 @@ -0,0 +1,75 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '5.0.0' } + +# Tests for Security/Enable-PrintSpoolerService.ps1 and Disable-PrintSpoolerService.ps1 (audit finding L6). +# The service control cmdlets are mocked. Nothing touches the real Print Spooler. + +. (Join-Path $PSScriptRoot 'TestHelpers.ps1') +$script:Elevated = Test-IsElevated + +BeforeAll { + . (Join-Path $PSScriptRoot 'TestHelpers.ps1') + $script:Enable = Get-RepoPath 'Security\Enable-PrintSpoolerService.ps1' + $script:Disable = Get-RepoPath 'Security\Disable-PrintSpoolerService.ps1' +} + +Describe 'Print Spooler scripts' -Skip:(-not $script:Elevated) { + BeforeEach { + foreach ($c in $script:StateChangingCommands) { Mock -CommandName $c -MockWith ([scriptblock]::Create("throw 'UNMOCKED state-changing call: $c'")) } + $global:IntuneTestState = @{ Status = 'Stopped'; StartType = 'Disabled'; Dependents = @(); Calls = @() } + Mock Get-Service { + [PSCustomObject]@{ Name = 'Spooler'; Status = $global:IntuneTestState.Status; StartType = $global:IntuneTestState.StartType; DependentServices = $global:IntuneTestState.Dependents } + } + Mock Set-Service { $global:IntuneTestState.Calls += "Set-Service $StartupType" } + Mock Start-Service { $global:IntuneTestState.Calls += 'Start-Service' } + Mock Stop-Service { $global:IntuneTestState.Calls += "Stop-Service force=$([bool]$Force)" } + Mock Start-Sleep { $global:IntuneTestState.Calls += "Start-Sleep $Seconds" } + } + AfterEach { Remove-Variable -Name IntuneTestState -Scope Global -ErrorAction SilentlyContinue } + + It 'Enable sets Automatic and starts the service without a 10 second wait (L6)' { + $r = Invoke-ScriptUnderTest -Path $script:Enable + $r.ExitCode | Should -Be 0 + $global:IntuneTestState.Calls | Should -Be @('Set-Service Automatic', 'Start-Service') + Should -Invoke Start-Sleep -Times 0 -Exactly + } + + It 'Enable -WhatIf changes nothing' { + $r = Invoke-ScriptUnderTest -Path $script:Enable -Arguments @{ WhatIf = $true } + $r.ExitCode | Should -Be 0 + $global:IntuneTestState.Calls.Count | Should -Be 0 + } + + It 'Disable stops WITHOUT -Force so dependent services are not stopped (L6)' { + $global:IntuneTestState.Status = 'Running'; $global:IntuneTestState.StartType = 'Automatic' + $r = Invoke-ScriptUnderTest -Path $script:Disable + $r.ExitCode | Should -Be 0 + $global:IntuneTestState.Calls | Should -Contain 'Stop-Service force=False' + $global:IntuneTestState.Calls | Should -Contain 'Set-Service Disabled' + } + + It 'Disable warns about running dependent services' { + $global:IntuneTestState.Status = 'Running' + $global:IntuneTestState.Dependents = @([PSCustomObject]@{ Name = 'FaxService'; Status = 'Running' }) + $r = Invoke-ScriptUnderTest -Path $script:Disable + $r.Output | Should -Match 'FaxService' + } + + It 'Disable exits 1 when Stop-Service fails because of a running dependent' { + $global:IntuneTestState.Status = 'Running' + Mock Stop-Service { throw 'Cannot stop service because it has running dependent services.' } + (Invoke-ScriptUnderTest -Path $script:Disable).ExitCode | Should -Be 1 + } + + It 'Disable -WhatIf changes nothing' { + $global:IntuneTestState.Status = 'Running' + (Invoke-ScriptUnderTest -Path $script:Disable -Arguments @{ WhatIf = $true }).ExitCode | Should -Be 0 + $global:IntuneTestState.Calls.Count | Should -Be 0 + } + + It 'neither script file has a BOM or a non-ASCII character' { + foreach ($p in @($script:Enable, $script:Disable)) { + $bytes = [System.IO.File]::ReadAllBytes($p) + ($bytes | Where-Object { $_ -gt 127 }).Count | Should -Be 0 + } + } +} diff --git a/Tests/Repair-MultipleIntuneMDMCert.Tests.ps1 b/Tests/Repair-MultipleIntuneMDMCert.Tests.ps1 new file mode 100644 index 0000000..96514a7 --- /dev/null +++ b/Tests/Repair-MultipleIntuneMDMCert.Tests.ps1 @@ -0,0 +1,60 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '5.0.0' } + +# Tests for Remediation/Repair-MultipleIntuneMDMCert.ps1 (audit finding M1). +# The certificate store is an in-memory list; nothing touches Cert:\LocalMachine\My. + +. (Join-Path $PSScriptRoot 'TestHelpers.ps1') +$script:Elevated = Test-IsElevated + +BeforeAll { + . (Join-Path $PSScriptRoot 'TestHelpers.ps1') + $script:ScriptPath = Get-RepoPath 'Remediation\Repair-MultipleIntuneMDMCert.ps1' + function New-FakeCert { + param([string]$Thumbprint, [datetime]$NotBefore, [string]$Issuer = 'CN=Microsoft Intune MDM Device CA') + [PSCustomObject]@{ Thumbprint = $Thumbprint; NotBefore = $NotBefore; Issuer = $Issuer; PSPath = "fake::$Thumbprint" } + } +} + +Describe 'Repair-MultipleIntuneMDMCert.ps1' -Skip:(-not $script:Elevated) { + BeforeEach { + foreach ($c in $script:StateChangingCommands) { Mock -CommandName $c -MockWith ([scriptblock]::Create("throw 'UNMOCKED state-changing call: $c'")) } + $global:IntuneTestState = @{ + Store = [System.Collections.ArrayList]@( + (New-FakeCert 'OLD' ([datetime]'2024-01-01')), + (New-FakeCert 'NEW' ([datetime]'2025-06-01')), + (New-FakeCert 'OTHER' ([datetime]'2020-01-01') 'CN=Something Else') + ) + } + Mock Test-Path { $true } + Mock Get-ChildItem { , @($global:IntuneTestState.Store) | ForEach-Object { $_ } } + Mock Remove-Item { $t = $global:IntuneTestState.Store | Where-Object { $_.PSPath -eq $Path } | Select-Object -First 1; if ($t) { $global:IntuneTestState.Store.Remove($t) } } + } + AfterEach { Remove-Variable -Name IntuneTestState -Scope Global -ErrorAction SilentlyContinue } + + It 'removes the older certificate, keeps the newest, exits 0' { + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath + $r.ExitCode | Should -Be 0 + Should -Invoke Remove-Item -Times 1 -Exactly -ParameterFilter { $Path -eq 'fake::OLD' } + ($global:IntuneTestState.Store.Thumbprint -contains 'NEW') | Should -BeTrue + ($global:IntuneTestState.Store.Thumbprint -contains 'OTHER') | Should -BeTrue + } + + It '-WhatIf removes nothing and exits 0 instead of failing verification (M1)' { + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments @{ WhatIf = $true } + $r.ExitCode | Should -Be 0 + Should -Invoke Remove-Item -Times 0 -Exactly + $global:IntuneTestState.Store.Count | Should -Be 3 + } + + It 'exits 0 and removes nothing when there is a single Intune certificate' { + $global:IntuneTestState.Store.RemoveAt(0) + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath + $r.ExitCode | Should -Be 0 + Should -Invoke Remove-Item -Times 0 -Exactly + } + + It 'exits 1 when a removal fails' { + Mock Remove-Item { throw 'access denied' } + (Invoke-ScriptUnderTest -Path $script:ScriptPath).ExitCode | Should -Be 1 + } +} diff --git a/Tests/Set-OfficeUpdateChannel.Tests.ps1 b/Tests/Set-OfficeUpdateChannel.Tests.ps1 new file mode 100644 index 0000000..07ef7a6 --- /dev/null +++ b/Tests/Set-OfficeUpdateChannel.Tests.ps1 @@ -0,0 +1,179 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '5.0.0' } + +# Tests for Remediation/Set-OfficeUpdateChannel.ps1 (audit finding C1, M1, M2, M4). +# Every cmdlet that can change the machine is mocked. Registry reads and writes go to an +# in-memory table, so the write, verify and exit-code path runs without touching HKLM. + +. (Join-Path $PSScriptRoot 'TestHelpers.ps1') +$script:Elevated = Test-IsElevated + +BeforeAll { + . (Join-Path $PSScriptRoot 'TestHelpers.ps1') + $script:ScriptPath = Get-RepoPath 'Remediation\Set-OfficeUpdateChannel.ps1' + + $script:CurrentCdn = 'http://officecdn.microsoft.com/pr/492350f6-3a01-4f97-b9c0-c7c6ddf67d60' + $script:SemiAnnualCdn = 'http://officecdn.microsoft.com/pr/7ffbc6bf-bc32-4f92-8982-f9dd17fd3114' + $script:C2RKey = 'HKLM:\SOFTWARE\Microsoft\Office\ClickToRun\Configuration' + $script:UpdaterSuffix = 'Microsoft Shared\ClickToRun\OfficeC2RClient.exe' + + # Shape of the real OfficeReleases payload: officeVersions is a list and every entry repeats the CDN URL + function New-ReleasePayload { + param([string[]]$SemiAnnualCdns = @($script:SemiAnnualCdn)) + $versions = 1..15 | ForEach-Object { [PSCustomObject]@{ legacyVersion = "16.0.$_"; cdnBaseUrl = $SemiAnnualCdns[($_ - 1) % $SemiAnnualCdns.Count] } } + @( + [PSCustomObject]@{ channelId = 'Current'; latestversion = '16.0.99999.1'; officeVersions = @([PSCustomObject]@{ cdnBaseUrl = $script:CurrentCdn }) }, + [PSCustomObject]@{ channelId = 'SemiAnnual'; latestversion = '16.0.17928.20700'; officeVersions = $versions } + ) + } + function Invoke-Under { param([hashtable]$Arguments = @{}) Invoke-ScriptUnderTest -Path $script:ScriptPath -Arguments $Arguments } +} + +Describe 'Set-OfficeUpdateChannel.ps1' -Skip:(-not $script:Elevated) { + BeforeEach { + if ($env:PROCESSOR_ARCHITEW6432) { throw 'This test must not run in a 32-bit host: the relaunch branch would start a real child process.' } + + # Unfiltered default mocks that throw for everything that can change the machine + foreach ($c in $script:StateChangingCommands) { Mock -CommandName $c -MockWith ([scriptblock]::Create("throw 'UNMOCKED state-changing call: $c'")) } + + # In-memory registry and switches. Mock bodies do not see $script: variables, so the state + # lives in one global table that AfterEach removes. + $global:IntuneTestState = @{ + Reg = @{ CDNBaseUrl = $script:CurrentCdn; VersionToReport = '16.0.1.1' } + C2RInstalled = $true + UpdaterExists = $true + Payload = (New-ReleasePayload) + C2RKey = $script:C2RKey + UpdaterSuffix = $script:UpdaterSuffix + } + + Mock Test-Path { + $p = "$Path" + if ($p -eq $global:IntuneTestState.C2RKey) { return $global:IntuneTestState.C2RInstalled } + if ($p -like "*$($global:IntuneTestState.UpdaterSuffix)") { return $global:IntuneTestState.UpdaterExists } + return $false + } + # Behave like the real cmdlets: Get-ItemPropertyValue THROWS for a missing value, Get-ItemProperty does not + Mock Get-ItemPropertyValue { + if (-not $global:IntuneTestState.Reg.ContainsKey($Name)) { throw "Property $Name does not exist at path $Path." } + $global:IntuneTestState.Reg[$Name] + } + Mock Get-ItemProperty { + $o = [PSCustomObject]@{} + foreach ($k in $global:IntuneTestState.Reg.Keys) { $o | Add-Member -NotePropertyName $k -NotePropertyValue $global:IntuneTestState.Reg[$k] } + $o + } + Mock Set-ItemProperty { $global:IntuneTestState.Reg[$Name] = $Value } + Mock Invoke-RestMethod { $global:IntuneTestState.Payload } + Mock Start-Process { [PSCustomObject]@{ ExitCode = 0 } } + Mock Start-Sleep { } + } + + AfterEach { + Remove-Variable -Name IntuneTestState -Scope Global -ErrorAction SilentlyContinue + } + + It 'has its safety net active (an unmocked state change throws)' { + { New-Item -Path (Join-Path $TestDrive 'x') -ItemType Directory } | Should -Throw '*UNMOCKED*' + } + + It 'writes ONE string, not an array, to CDNBaseUrl and exits 0 (C1)' { + $r = Invoke-Under + $r.ExitCode | Should -Be 0 + # -BeOfType passes each element of an array, so test the value itself + ($global:IntuneTestState.Reg['CDNBaseUrl'] -is [string]) | Should -BeTrue + @($global:IntuneTestState.Reg['CDNBaseUrl']).Count | Should -Be 1 + $global:IntuneTestState.Reg['CDNBaseUrl'] | Should -Be $script:SemiAnnualCdn + Should -Invoke Set-ItemProperty -Times 1 -Exactly + } + + It 'launches the Click-to-Run updater from Common Files (C1)' { + $r = Invoke-Under + $r.ExitCode | Should -Be 0 + Should -Invoke Start-Process -Times 1 -Exactly -ParameterFilter { $FilePath -like '*Microsoft Shared\ClickToRun\OfficeC2RClient.exe' } + } + + It 'does not crash when CDNBaseUrl or VersionToReport is missing from the registry (the H1 pattern)' { + $global:IntuneTestState.Reg.Clear() + $r = Invoke-Under + $r.ExitCode | Should -Be 0 + $global:IntuneTestState.Reg['CDNBaseUrl'] | Should -Be $script:SemiAnnualCdn + } + + It 'exits 1 when the updater is missing, instead of warning and carrying on (C1)' { + $global:IntuneTestState.UpdaterExists = $false + $r = Invoke-Under + $r.ExitCode | Should -Be 1 + Should -Invoke Start-Process -Times 0 -Exactly + } + + It 'exits 1 when the updater returns a non-zero code' { + Mock Start-Process { [PSCustomObject]@{ ExitCode = 5 } } + (Invoke-Under).ExitCode | Should -Be 1 + } + + It 'exits 1 and writes nothing when the channel has more than one distinct CDN URL' { + $global:IntuneTestState.Payload = New-ReleasePayload -SemiAnnualCdns @($script:SemiAnnualCdn, 'http://officecdn.microsoft.com/pr/other') + $r = Invoke-Under + $r.ExitCode | Should -Be 1 + Should -Invoke Set-ItemProperty -Times 0 -Exactly + } + + It 'exits 1 when the releases API fails' { + Mock Invoke-RestMethod { throw 'boom' } + (Invoke-Under).ExitCode | Should -Be 1 + } + + It 'exits 0 and writes nothing when already on Semi-Annual and the latest version' { + $global:IntuneTestState.Reg['CDNBaseUrl'] = $script:SemiAnnualCdn + $global:IntuneTestState.Reg['VersionToReport'] = '16.0.17928.20700' + $r = Invoke-Under + $r.ExitCode | Should -Be 0 + Should -Invoke Set-ItemProperty -Times 0 -Exactly + Should -Invoke Start-Process -Times 0 -Exactly + } + + It 'exits 0 as not applicable when Click-to-Run is not installed, without calling the API (M4)' { + $global:IntuneTestState.C2RInstalled = $false + $r = Invoke-Under + $r.ExitCode | Should -Be 0 + $r.Output | Should -Match 'Not applicable' + Should -Invoke Invoke-RestMethod -Times 0 -Exactly + } + + It '-WhatIf makes no changes and exits 0 instead of failing verification (M1)' { + $r = Invoke-Under -Arguments @{ WhatIf = $true } + $r.ExitCode | Should -Be 0 + Should -Invoke Set-ItemProperty -Times 0 -Exactly + Should -Invoke Start-Process -Times 0 -Exactly + $global:IntuneTestState.Reg['CDNBaseUrl'] | Should -Be $script:CurrentCdn + } +} + +Describe 'Set-OfficeUpdateChannel.ps1 helper functions' { + BeforeAll { + . ([scriptblock]::Create((Import-ScriptFunction -Path $script:ScriptPath -Name 'Get-RelaunchArgumentList', 'Get-ChannelInfo'))) + } + + It 'forwards -WhatIf and -Verbose to the 64-bit relaunch (M2/M3 pattern)' { + $a = Get-RelaunchArgumentList -ScriptPath 'C:\x\s.ps1' -BoundParameters @{ WhatIf = [switch]$true; Verbose = [switch]$true } + $a | Should -Contain '-WhatIf' + $a | Should -Contain '-Verbose' + $a | Should -Contain 'C:\x\s.ps1' + } + + It 'does not forward a switch that was not present' { + $a = Get-RelaunchArgumentList -ScriptPath 'C:\x\s.ps1' -BoundParameters @{ WhatIf = [switch]$false } + $a | Should -Not -Contain '-WhatIf' + } + + It 'collapses the 15 repeated CDN entries to a single string' { + $info = Get-ChannelInfo -CloudVersionInfo (New-ReleasePayload) -ChannelId 'SemiAnnual' + ($info.CdnBaseUrl -is [string]) | Should -BeTrue + $info.CdnBaseUrl | Should -Be $script:SemiAnnualCdn + $info.LatestVersion | Should -Be '16.0.17928.20700' + } + + It 'throws when the channel is missing' { + { Get-ChannelInfo -CloudVersionInfo (New-ReleasePayload) -ChannelId 'Nope' } | Should -Throw '*Could not find*' + } +} diff --git a/Tests/SmartCardLogonEnforcement.Tests.ps1 b/Tests/SmartCardLogonEnforcement.Tests.ps1 new file mode 100644 index 0000000..7540e93 --- /dev/null +++ b/Tests/SmartCardLogonEnforcement.Tests.ps1 @@ -0,0 +1,245 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '5.0.0' } + +# Tests for Security/Enable-SmartCardLogonEnforcement.ps1 and Disable-SmartCardLogonEnforcement.ps1 +# (audit findings H3 lockout guard, H4 false success and deleted log, M3 dropped -WhatIf, L2 phantom key). +# The registry, services, log file and hardware list are in-memory. No real registry write can happen: +# every state-changing cmdlet has an unfiltered default mock that throws. + +. (Join-Path $PSScriptRoot 'TestHelpers.ps1') +$script:Elevated = Test-IsElevated + +BeforeAll { + . (Join-Path $PSScriptRoot 'TestHelpers.ps1') + $script:Enable = Get-RepoPath 'Security\Enable-SmartCardLogonEnforcement.ps1' + $script:Disable = Get-RepoPath 'Security\Disable-SmartCardLogonEnforcement.ps1' + $script:SysKey = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' + $script:WinKey = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' + $script:SvcKey = 'HKLM:\SYSTEM\CurrentControlSet\Services\SCPolicySvc' +} + +Describe 'Smart card logon scripts' -Skip:(-not $script:Elevated) { + BeforeEach { + if ($env:PROCESSOR_ARCHITEW6432) { throw 'This test must not run in a 32-bit host: the relaunch branch would start a real child process.' } + foreach ($c in $script:StateChangingCommands) { Mock -CommandName $c -MockWith ([scriptblock]::Create("throw 'UNMOCKED state-changing call: $c'")) } + + $global:IntuneTestState = @{ + Keys = [System.Collections.ArrayList]@($script:SysKey, $script:WinKey, $script:SvcKey) + Values = @{} + Readers = @([PSCustomObject]@{ Name = 'Fake Reader'; Status = 'OK' }) + StartType = 'Manual' + ServiceSet = @() + Log = [System.Collections.ArrayList]@() + WriteFails = $false + WriteFailsFor = $null # when set, only a write to this value name fails + ServiceFails = $false + ReadBackName = $null # when set, ReadBack applies only to this value name + ReadBack = $null # when set, Get-ItemProperty returns this instead of the stored value + } + + Mock Test-Path { $p = "$Path$LiteralPath"; if ($p -like '*IntuneManagementExtension*') { return $true }; $global:IntuneTestState.Keys -contains $p } + Mock New-Item { [void]$global:IntuneTestState.Keys.Add("$Path") } + Mock New-ItemProperty { + if ($global:IntuneTestState.WriteFails -or ($global:IntuneTestState.WriteFailsFor -and $Name -eq $global:IntuneTestState.WriteFailsFor)) { throw 'Requested registry access is not allowed.' } + $global:IntuneTestState.Values["$LiteralPath|$Name"] = $Value + } + Mock Get-ItemProperty { + $n = @($Name)[0] + $v = $global:IntuneTestState.Values["$LiteralPath|$n"] + if ($null -ne $global:IntuneTestState.ReadBack -and (-not $global:IntuneTestState.ReadBackName -or $n -eq $global:IntuneTestState.ReadBackName)) { $v = $global:IntuneTestState.ReadBack } + $o = [PSCustomObject]@{} + $o | Add-Member -NotePropertyName $n -NotePropertyValue $v + $o + } + Mock Get-CimInstance { $global:IntuneTestState.Readers } + Mock Set-Service { if ($global:IntuneTestState.ServiceFails) { throw 'Access is denied' }; $global:IntuneTestState.ServiceSet += "$Name=$StartupType"; $global:IntuneTestState.StartType = "$StartupType" } + Mock Get-Service { [PSCustomObject]@{ Name = 'SCPolicySvc'; StartType = $global:IntuneTestState.StartType } } + Mock Add-Content { [void]$global:IntuneTestState.Log.Add("$Value") } + Mock Start-Sleep { } + } + AfterEach { Remove-Variable -Name IntuneTestState -Scope Global -ErrorAction SilentlyContinue } + + Context 'Enable-SmartCardLogonEnforcement.ps1' { + It 'writes the three DWORDs, sets the service, verifies, exits 0 and keeps its log (H4)' { + $r = Invoke-ScriptUnderTest -Path $script:Enable + $r.ExitCode | Should -Be 0 + $v = $global:IntuneTestState.Values + $v["$($script:SysKey)|scforceoption"] | Should -Be 1 + $v["$($script:WinKey)|ScRemoveOption"] | Should -Be 1 + $v["$($script:SvcKey)|Start"] | Should -Be 2 + $global:IntuneTestState.ServiceSet | Should -Contain 'SCPolicySvc=Automatic' + Should -Invoke Remove-Item -Times 0 -Exactly + ($global:IntuneTestState.Log -join "`n") | Should -Match 'completed successfully' + } + + It 'writes DWORD values, not strings' { + Invoke-ScriptUnderTest -Path $script:Enable | Out-Null + Should -Invoke New-ItemProperty -Times 3 -Exactly -ParameterFilter { $PropertyType -eq 'DWord' } + } + + It 'REFUSES with exit 1 and changes nothing when there is no smart card reader (H3)' { + $global:IntuneTestState.Readers = @() + $r = Invoke-ScriptUnderTest -Path $script:Enable + $r.ExitCode | Should -Be 1 + $r.Output | Should -Match 'lock every user out' + Should -Invoke New-ItemProperty -Times 0 -Exactly + Should -Invoke New-Item -Times 0 -Exactly + Should -Invoke Set-Service -Times 0 -Exactly + } + + It 'ignores a reader that is not in a healthy state (H3)' { + $global:IntuneTestState.Readers = @([PSCustomObject]@{ Name = 'Broken Reader'; Status = 'Error' }) + (Invoke-ScriptUnderTest -Path $script:Enable).ExitCode | Should -Be 1 + Should -Invoke New-ItemProperty -Times 0 -Exactly + } + + It 'proceeds past the guard with -Force when there is no reader' { + $global:IntuneTestState.Readers = @() + $r = Invoke-ScriptUnderTest -Path $script:Enable -Arguments @{ Force = $true } + $r.ExitCode | Should -Be 0 + $global:IntuneTestState.Values["$($script:SysKey)|scforceoption"] | Should -Be 1 + } + + It 'exits 1 when a registry write fails instead of reporting success (H4)' { + $global:IntuneTestState.WriteFails = $true + $r = Invoke-ScriptUnderTest -Path $script:Enable + $r.ExitCode | Should -Be 1 + $r.Output | Should -Match 'NOT fully applied' + } + + It 'does NOT require a smart card when the service step fails: scforceoption is never written (review blocker)' { + $global:IntuneTestState.ServiceFails = $true + $r = Invoke-ScriptUnderTest -Path $script:Enable + $r.ExitCode | Should -Be 1 + $global:IntuneTestState.Values.ContainsKey("$($script:SysKey)|scforceoption") | Should -BeFalse + $r.Output | Should -Match 'Not enforcing|NOT fully applied' + } + + It 'does not write scforceoption when ScRemoveOption failed' { + $global:IntuneTestState.WriteFailsFor = 'ScRemoveOption' + $r = Invoke-ScriptUnderTest -Path $script:Enable + $r.ExitCode | Should -Be 1 + $global:IntuneTestState.Values.ContainsKey("$($script:SysKey)|scforceoption") | Should -BeFalse + } + + It 'writes scforceoption last, after the removal option and the service' { + $global:IntuneTestState.Order = @() + Mock New-ItemProperty { $global:IntuneTestState.Order += "$Name"; $global:IntuneTestState.Values["$LiteralPath|$Name"] = $Value } + Invoke-ScriptUnderTest -Path $script:Enable | Out-Null + $global:IntuneTestState.Order[-1] | Should -Be 'scforceoption' + $global:IntuneTestState.Order | Should -Contain 'ScRemoveOption' + } + + It 'rolls scforceoption back to its previous value when its own read-back fails' { + $global:IntuneTestState.Values["$($script:SysKey)|scforceoption"] = 0 + $global:IntuneTestState.ReadBack = 0 + $global:IntuneTestState.ReadBackName = 'scforceoption' + $r = Invoke-ScriptUnderTest -Path $script:Enable + $r.ExitCode | Should -Be 1 + $global:IntuneTestState.Values["$($script:SysKey)|scforceoption"] | Should -Be 0 + ($global:IntuneTestState.Log -join "`n") | Should -Match 'Rolled scforceoption back to 0' + } + + It 'rolls back to 0 when there was no previous scforceoption value and its write fails' { + $global:IntuneTestState.WriteFailsFor = 'scforceoption' + $r = Invoke-ScriptUnderTest -Path $script:Enable + $r.ExitCode | Should -Be 1 + # the rollback write also fails in this setup, which must be reported, not hidden + $r.Output | Should -Match 'rollback' + } + + It 'exits 1 when the read-back does not match what was written (H4)' { + $global:IntuneTestState.ReadBack = 0 + (Invoke-ScriptUnderTest -Path $script:Enable).ExitCode | Should -Be 1 + } + + It 'does not create a phantom SCPolicySvc key, and fails, when the service key is missing (L2)' { + # The reader preflight also needs the key, so use -Force to reach the service section + [void]$global:IntuneTestState.Keys.Remove($script:SvcKey) + $r = Invoke-ScriptUnderTest -Path $script:Enable -Arguments @{ Force = $true } + $r.ExitCode | Should -Be 1 + Should -Invoke New-Item -Times 0 -Exactly -ParameterFilter { "$Path" -like '*SCPolicySvc*' } + } + + It 'refuses without -Force when the service key is missing (H3)' { + [void]$global:IntuneTestState.Keys.Remove($script:SvcKey) + $r = Invoke-ScriptUnderTest -Path $script:Enable + $r.ExitCode | Should -Be 1 + Should -Invoke New-ItemProperty -Times 0 -Exactly + } + + It '-WhatIf changes nothing at all, writes no log, and exits 0 (M3)' { + $r = Invoke-ScriptUnderTest -Path $script:Enable -Arguments @{ WhatIf = $true } + $r.ExitCode | Should -Be 0 + Should -Invoke New-ItemProperty -Times 0 -Exactly + Should -Invoke New-Item -Times 0 -Exactly + Should -Invoke Set-Service -Times 0 -Exactly + Should -Invoke Add-Content -Times 0 -Exactly + Should -Invoke Remove-Item -Times 0 -Exactly + } + + It '-WhatIf with no reader reports the refusal but still changes nothing and exits 0' { + $global:IntuneTestState.Readers = @() + $r = Invoke-ScriptUnderTest -Path $script:Enable -Arguments @{ WhatIf = $true } + $r.ExitCode | Should -Be 0 + $r.Output | Should -Match 'would refuse' + Should -Invoke New-ItemProperty -Times 0 -Exactly + } + } + + Context 'Disable-SmartCardLogonEnforcement.ps1' { + It 'writes the three DWORDs (0, 0, Start 4), disables the service, verifies, exits 0, keeps its log (H4)' { + $r = Invoke-ScriptUnderTest -Path $script:Disable + $r.ExitCode | Should -Be 0 + $v = $global:IntuneTestState.Values + $v["$($script:SysKey)|scforceoption"] | Should -Be 0 + $v["$($script:WinKey)|ScRemoveOption"] | Should -Be 0 + $v["$($script:SvcKey)|Start"] | Should -Be 4 + $global:IntuneTestState.ServiceSet | Should -Contain 'SCPolicySvc=Disabled' + Should -Invoke Remove-Item -Times 0 -Exactly + } + + It 'is not blocked by the reader guard (it only loosens enforcement)' { + $global:IntuneTestState.Readers = @() + (Invoke-ScriptUnderTest -Path $script:Disable).ExitCode | Should -Be 0 + } + + It 'exits 1 when a registry write fails (H4)' { + $global:IntuneTestState.WriteFails = $true + (Invoke-ScriptUnderTest -Path $script:Disable).ExitCode | Should -Be 1 + } + + It 'skips the service and creates no phantom key when SCPolicySvc does not exist (L2)' { + [void]$global:IntuneTestState.Keys.Remove($script:SvcKey) + $r = Invoke-ScriptUnderTest -Path $script:Disable + $r.ExitCode | Should -Be 0 + Should -Invoke New-Item -Times 0 -Exactly -ParameterFilter { "$Path" -like '*SCPolicySvc*' } + Should -Invoke Set-Service -Times 0 -Exactly + } + + It '-WhatIf changes nothing at all and exits 0 (M3)' { + $r = Invoke-ScriptUnderTest -Path $script:Disable -Arguments @{ WhatIf = $true } + $r.ExitCode | Should -Be 0 + Should -Invoke New-ItemProperty -Times 0 -Exactly + Should -Invoke New-Item -Times 0 -Exactly + Should -Invoke Set-Service -Times 0 -Exactly + Should -Invoke Add-Content -Times 0 -Exactly + } + } +} + +Describe 'Smart card scripts: 64-bit relaunch argument forwarding (M3)' { + It 'forwards to the 64-bit child in ' -ForEach @( + @{ File = 'Enable-SmartCardLogonEnforcement.ps1'; Switch = 'WhatIf' }, + @{ File = 'Enable-SmartCardLogonEnforcement.ps1'; Switch = 'Force' }, + @{ File = 'Enable-SmartCardLogonEnforcement.ps1'; Switch = 'KeepLogs' }, + @{ File = 'Disable-SmartCardLogonEnforcement.ps1'; Switch = 'WhatIf' }, + @{ File = 'Disable-SmartCardLogonEnforcement.ps1'; Switch = 'KeepLogs' } + ) { + . ([scriptblock]::Create((Import-ScriptFunction -Path (Get-RepoPath "Security\$File") -Name 'Get-RelaunchArgumentList'))) + $bound = @{} + $bound[$Switch] = [switch]$true + $a = Get-RelaunchArgumentList -ScriptPath 'C:\x\s.ps1' -BoundParameters $bound + $a | Should -Contain "-$Switch" + $a | Should -Contain '-File' + } +} diff --git a/Tests/Start-MDMSync.Tests.ps1 b/Tests/Start-MDMSync.Tests.ps1 new file mode 100644 index 0000000..157d033 --- /dev/null +++ b/Tests/Start-MDMSync.Tests.ps1 @@ -0,0 +1,77 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '5.0.0' } + +# Tests for Troubleshooting/Start-MDMSync.ps1 (audit finding H7). +# The script itself needs Windows PowerShell 5.1 and a real MDM session, so the tests extract its +# functions and feed them fake session objects. No sync is ever started. + +. (Join-Path $PSScriptRoot 'TestHelpers.ps1') + +BeforeAll { + . (Join-Path $PSScriptRoot 'TestHelpers.ps1') + $script:ScriptPath = Get-RepoPath 'Troubleshooting\Start-MDMSync.ps1' + . ([scriptblock]::Create((Import-ScriptFunction -Path $script:ScriptPath -Name 'Get-MdmSessionError', 'Wait-MdmSession', 'Get-MdmSyncExitCode'))) + + # A fake session whose State advances one step per Start-Sleep call + function New-FakeSession { + param([string[]]$States, $ExtendedError = $null) + $global:IntuneTestState = @{ Index = 0; States = $States } + $s = [PSCustomObject]@{ State = $States[0]; ExtendedError = $ExtendedError } + $global:IntuneTestState.Session = $s + $s + } +} + +Describe 'Start-MDMSync.ps1' { + BeforeEach { + Mock Start-Sleep { + $st = $global:IntuneTestState + if ($st.Index -lt ($st.States.Count - 1)) { $st.Index++ } + $st.Session.State = $st.States[$st.Index] + } + } + AfterEach { Remove-Variable -Name IntuneTestState -Scope Global -ErrorAction SilentlyContinue } + + It 'declares Windows PowerShell 5.1 Desktop so PowerShell 7 gets a clear error, not a type-load failure' { + $text = Get-Content -Path $script:ScriptPath -Raw + $text | Should -Match '(?m)^#Requires -PSEdition Desktop' + $text | Should -Match '(?m)^#Requires -Version 5\.1' + } + + It 'returns exit 0 when the session reaches Completed with no error' { + $s = New-FakeSession -States 'Starting', 'Connecting', 'Communicating', 'Completed' + $r = Wait-MdmSession -Session $s -TimeoutSeconds 60 -CheckIntervalSeconds 5 + $r.State | Should -Be 'Completed' + $r.TimedOut | Should -BeFalse + Get-MdmSyncExitCode -Result $r | Should -Be 0 + } + + It 'returns exit 1 when the session Completed but ExtendedError is set (H7)' { + # COMException sets HResult through its constructor; Exception.HResult has no public setter in Windows PowerShell 5.1 + $err = [System.Runtime.InteropServices.COMException]::new('http error', [int]0x80190190) + $s = New-FakeSession -States 'Starting', 'Completed' -ExtendedError $err + $r = Wait-MdmSession -Session $s -TimeoutSeconds 60 -CheckIntervalSeconds 5 + $r.Error | Should -Be '0x80190190' + Get-MdmSyncExitCode -Result $r | Should -Be 1 + } + + It 'treats ExtendedError with HResult 0 as no error' { + $ok = [System.Runtime.InteropServices.COMException]::new('ok', 0) + Get-MdmSessionError -Session ([PSCustomObject]@{ ExtendedError = $ok }) | Should -BeNullOrEmpty + Get-MdmSessionError -Session ([PSCustomObject]@{ ExtendedError = $null }) | Should -BeNullOrEmpty + } + + It 'returns exit 2 on timeout, even after many identical states (the old code exited 1 after 6)' { + $s = New-FakeSession -States 'Connecting' + $r = Wait-MdmSession -Session $s -TimeoutSeconds 60 -CheckIntervalSeconds 5 + $r.TimedOut | Should -BeTrue + Get-MdmSyncExitCode -Result $r | Should -Be 2 + Should -Invoke Start-Sleep -Times 12 -Exactly + } + + It 'does not treat Retrying or AlertStatusAvailable as an end state' { + $s = New-FakeSession -States 'Starting', 'Retrying', 'AlertStatusAvailable', 'Completed' + $r = Wait-MdmSession -Session $s -TimeoutSeconds 60 -CheckIntervalSeconds 5 + $r.State | Should -Be 'Completed' + Get-MdmSyncExitCode -Result $r | Should -Be 0 + } +} diff --git a/Tests/Test-IntuneConnectivity.Tests.ps1 b/Tests/Test-IntuneConnectivity.Tests.ps1 new file mode 100644 index 0000000..388eef9 --- /dev/null +++ b/Tests/Test-IntuneConnectivity.Tests.ps1 @@ -0,0 +1,201 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '5.0.0' } + +# Tests for Troubleshooting/Test-IntuneConnectivity.ps1 (audit findings H2 and M12). +# The script's functions are extracted from the file by AST. Network calls are mocked. + +. (Join-Path $PSScriptRoot 'TestHelpers.ps1') + +BeforeAll { + . (Join-Path $PSScriptRoot 'TestHelpers.ps1') + $script:ScriptPath = Get-RepoPath 'Troubleshooting\Test-IntuneConnectivity.ps1' + $names = 'Invoke-EndpointApiWithRetry', 'ConvertFrom-NetshProxyOutput', 'Get-ProxySettings', 'Get-EndpointList', + 'Get-M365CommonEndpointList', 'Get-IntuneEndpointList', 'Get-EndpointRegionNote', 'Test-EndpointReachable', + 'Test-EndpointSet', 'Test-DeviceIntuneConnectivity' + . ([scriptblock]::Create((Import-ScriptFunction -Path $script:ScriptPath -Name $names))) + + function New-HttpFailure { + param([int]$StatusCode) + $ex = [System.Exception]::new("HTTP $StatusCode") + $ex | Add-Member -NotePropertyName Response -NotePropertyValue ([PSCustomObject]@{ StatusCode = $StatusCode }) + $ex + } +} + +Describe 'ConvertFrom-NetshProxyOutput (M12)' { + It 'keeps the whole host name. The old TrimStart() ate leading characters of the proxy name' { + ConvertFrom-NetshProxyOutput -Lines @('Current WinHTTP proxy settings:', '', ' Proxy Server(s) : server1.contoso.com:8080', ' Bypass List : (none)') | + Should -Be 'http://server1.contoso.com:8080' + } + It 'keeps a proxy name that starts with a character from the old trim set' { + ConvertFrom-NetshProxyOutput -Lines @(' Proxy Server(s) : sysproxy:3128') | Should -Be 'http://sysproxy:3128' + } + It 'returns NoProxy for direct access' { + ConvertFrom-NetshProxyOutput -Lines @('Current WinHTTP proxy settings:', '', ' Direct access (no proxy server).') | Should -Be 'NoProxy' + } + It 'picks the https entry of a per-protocol list' { + ConvertFrom-NetshProxyOutput -Lines @(' Proxy Server(s) : http=a.test:80;https=b.test:443') | Should -Be 'http://b.test:443' + } + It 'does not double the scheme' { + ConvertFrom-NetshProxyOutput -Lines @(' Proxy Server(s) : http://p.test:8080') | Should -Be 'http://p.test:8080' + } + It 'returns a string, never an array' { + $proxy = ConvertFrom-NetshProxyOutput -Lines @('x', ' Proxy Server(s) : p.test:1', ' Proxy Server(s) : q.test:2') + ($proxy -is [string]) | Should -BeTrue + } +} + +Describe 'Get-EndpointRegionNote' { + It 'maps to ' -ForEach @( + @{ Url = 'intunemaape1.eus.attest.azure.net'; Region = 'North America' }, + @{ Url = 'intunemaape10.weu.attest.azure.net'; Region = 'Europe' }, + @{ Url = 'intunemaape13.jpe.attest.azure.net'; Region = 'Asia & Pacific' }, + @{ Url = 'naprodimedata.blob.core.windows.net'; Region = 'North America' }, + @{ Url = 'manage.microsoft.com'; Region = '' } + ) { + Get-EndpointRegionNote -Url $Url | Should -Be $Region + } +} + +Describe 'Intune endpoint retrieval (H2)' { + BeforeEach { + $global:IntuneTestState = @{ MemFails = $false; CommonFails = $false; WebFails = @{}; WebCalls = @() } + Mock Start-Sleep { } + Mock Invoke-RestMethod { + $uri = "$Uri" + if ($uri -like '*ServiceAreas=MEM*') { + if ($global:IntuneTestState.MemFails) { throw 'MEM service down' } + return @( + [PSCustomObject]@{ id = 163; ServiceArea = 'MEM'; urls = @('*.manage.microsoft.com', 'manage.microsoft.com'); tcpPorts = '443'; required = $true }, + [PSCustomObject]@{ id = 165; ServiceArea = 'MEM'; urls = @('time.windows.com'); udpPorts = '123'; required = $true }, + [PSCustomObject]@{ id = 9999; ServiceArea = 'MEM'; urls = @('newservice.example.test'); tcpPorts = '443'; required = $true }, + [PSCustomObject]@{ id = 178; ServiceArea = 'MEM'; urls = @('apple.example.test'); tcpPorts = '443'; required = $false } + ) + } + if ($uri -like '*ServiceAreas=Common*') { + if ($global:IntuneTestState.CommonFails) { throw 'Common service down' } + return @( + [PSCustomObject]@{ id = 56; ServiceArea = 'Common'; urls = @('*.office.com', 'www.office.com'); tcpPorts = '80,443'; required = $true }, + [PSCustomObject]@{ id = 59; ServiceArea = 'Common'; urls = @('*.microsoftonline.com'); tcpPorts = '443'; required = $true } + ) + } + throw "unexpected uri $uri" + } + Mock Invoke-WebRequest { + $global:IntuneTestState.WebCalls += "$Uri" + foreach ($k in $global:IntuneTestState.WebFails.Keys) { + if ("$Uri" -like "*$k*") { throw $global:IntuneTestState.WebFails[$k] } + } + [PSCustomObject]@{ StatusCode = 200 } + } + Mock Get-ProxySettings { 'NoProxy' } + } + AfterEach { Remove-Variable -Name IntuneTestState -Scope Global -ErrorAction SilentlyContinue } + + It 'Get-IntuneEndpointList reaches Invoke-EndpointApiWithRetry and returns items (the old call was out of scope)' { + $list = @(Get-IntuneEndpointList) + $list.Count | Should -Be 4 + ($list | Where-Object id -eq 163).category | Should -Be 'Global' + ($list | Where-Object id -eq 163).urls | Should -Be @('manage.microsoft.com') + ($list | Where-Object id -eq 163).mandatory | Should -BeTrue + } + + It 'keeps endpoint IDs that are not in the category table, flagged as not known (M12)' { + $unknown = @(Get-IntuneEndpointList) | Where-Object id -eq 9999 + $unknown.category | Should -Be 'Other (id 9999)' + $unknown.known | Should -BeFalse + $unknown.mandatory | Should -BeTrue + } + + It 'keeps wildcard-only entries out of the URLs to test' { + $e = @(Get-M365CommonEndpointList) | Where-Object id -eq 59 + @($e.urls).Count | Should -Be 0 + $e.wildcardUrls | Should -Be @('*.microsoftonline.com') + } + + It 'throws when the service fails instead of returning an empty list' { + $global:IntuneTestState.MemFails = $true + { Get-IntuneEndpointList } | Should -Throw '*MEM service down*' + } + + It 'passes when every mandatory endpoint answers' { + $ErrorActionPreference = 'Continue' + Test-DeviceIntuneConnectivity | Should -BeTrue + $global:IntuneTestState.WebCalls | Should -Contain 'https://manage.microsoft.com/' + $global:IntuneTestState.WebCalls | Should -Not -Contain 'https://apple.example.test/' + # not in the built-in tables, so listed as NOT TESTED rather than tested or hidden + $global:IntuneTestState.WebCalls | Should -Not -Contain 'https://newservice.example.test/' + } + + It 'tests endpoint IDs outside the built-in tables with -IncludeUnlisted, using their required flag' { + $ErrorActionPreference = 'Continue' + Test-DeviceIntuneConnectivity -IncludeUnlisted | Should -BeTrue + $global:IntuneTestState.WebCalls | Should -Contain 'https://newservice.example.test/' + $global:IntuneTestState.WebCalls | Should -Not -Contain 'https://apple.example.test/' + } + + It 'fails on an unlisted endpoint that is down when -IncludeUnlisted is used' { + $ErrorActionPreference = 'Continue' + $global:IntuneTestState.WebFails['newservice.example.test'] = [System.Exception]::new('timed out') + Test-DeviceIntuneConnectivity -IncludeUnlisted | Should -BeFalse + Test-DeviceIntuneConnectivity | Should -BeTrue + } + + It 'never requests a wildcard-only domain such as microsoftonline.com (it has no address record)' { + $ErrorActionPreference = 'Continue' + Test-DeviceIntuneConnectivity | Should -BeTrue + ($global:IntuneTestState.WebCalls | Where-Object { $_ -like '*microsoftonline*' }) | Should -BeNullOrEmpty + ($global:IntuneTestState.WebCalls | Where-Object { $_ -like '*`**' }) | Should -BeNullOrEmpty + } + + It 'FAILS when the Intune list cannot be retrieved even though the M365 list works (H2)' { + $ErrorActionPreference = 'Continue' + $global:IntuneTestState.MemFails = $true + Test-DeviceIntuneConnectivity 2>$null | Should -BeFalse + # and nothing was reported as success for Intune + $global:IntuneTestState.WebCalls | Should -Not -Contain 'https://manage.microsoft.com/' + } + + It 'FAILS when the M365 list cannot be retrieved' { + $ErrorActionPreference = 'Continue' + $global:IntuneTestState.CommonFails = $true + Test-DeviceIntuneConnectivity 2>$null | Should -BeFalse + } + + It 'FAILS when the Intune list comes back empty' { + $ErrorActionPreference = 'Continue' + Mock Get-IntuneEndpointList { @() } + Test-DeviceIntuneConnectivity 2>$null | Should -BeFalse + } + + It 'counts an endpoint that answers 403 as reachable (M12)' { + $ErrorActionPreference = 'Continue' + $global:IntuneTestState.WebFails['manage.microsoft.com'] = (New-HttpFailure -StatusCode 403) + Test-DeviceIntuneConnectivity | Should -BeTrue + } + + It 'counts a timeout or DNS failure (no HTTP response) as failed' { + $ErrorActionPreference = 'Continue' + $global:IntuneTestState.WebFails['manage.microsoft.com'] = [System.Exception]::new('The operation timed out') + Test-DeviceIntuneConnectivity | Should -BeFalse + } + + It 'falls back to http when https gets no answer, as for CRL/OCSP hosts that serve port 80 only' { + $ErrorActionPreference = 'Continue' + $global:IntuneTestState.WebFails['https://www.office.com'] = [System.Exception]::new('The SSL connection could not be established') + Test-DeviceIntuneConnectivity | Should -BeTrue + $global:IntuneTestState.WebCalls | Should -Contain 'http://www.office.com/' + } + + It 'fails when both https and http get no answer' { + $ErrorActionPreference = 'Continue' + $global:IntuneTestState.WebFails['www.office.com'] = [System.Exception]::new('No such host is known') + Test-DeviceIntuneConnectivity | Should -BeFalse + } + + It 'skips a UDP-only endpoint (NTP) instead of failing it over HTTP' { + $ErrorActionPreference = 'Continue' + Test-DeviceIntuneConnectivity | Should -BeTrue + $global:IntuneTestState.WebCalls | Should -Not -Contain 'https://time.windows.com/' + $global:IntuneTestState.WebCalls | Should -Not -Contain 'http://time.windows.com/' + } +} diff --git a/Tests/Test-IntuneEnrollment.Tests.ps1 b/Tests/Test-IntuneEnrollment.Tests.ps1 new file mode 100644 index 0000000..72c7660 --- /dev/null +++ b/Tests/Test-IntuneEnrollment.Tests.ps1 @@ -0,0 +1,88 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '5.0.0' } + +# Tests for Troubleshooting/Test-IntuneEnrollment.ps1 (audit finding H1). +# The Enrollments key always holds subkeys with no ProviderID. Get-ItemPropertyValue threw on them and +# the script crashed with exit 1 before it judged anything. The registry here is an in-memory table. + +. (Join-Path $PSScriptRoot 'TestHelpers.ps1') + +BeforeAll { + . (Join-Path $PSScriptRoot 'TestHelpers.ps1') + $script:ScriptPath = Get-RepoPath 'Troubleshooting\Test-IntuneEnrollment.ps1' + $script:Root = 'HKLM:\SOFTWARE\Microsoft\Enrollments' +} + +Describe 'Test-IntuneEnrollment.ps1' { + BeforeEach { + foreach ($c in $script:StateChangingCommands) { Mock -CommandName $c -MockWith ([scriptblock]::Create("throw 'UNMOCKED state-changing call: $c'")) } + + # Subkeys as they exist on a real device: some have no ProviderID at all + $global:IntuneTestState = @{ + Root = $script:Root + Keys = @{ + "$($script:Root)\Context" = @{} + "$($script:Root)\Status" = @{} + "$($script:Root)\ValidNodePaths" = @{} + "$($script:Root)\18DCFFD4-AAAA" = @{} + "$($script:Root)\11111111-2222" = @{ ProviderID = 'MS DM Server'; EnrollmentState = 1; EnrollmentType = 6; UPN = 'user@example.test'; FirstSyncTime = 1700000000 } + "$($script:Root)\11111111-2222\DMClient\MS DM Server" = @{ EntDMID = 'abcd-1234' } + } + Service = $null + } + + Mock Test-Path { $global:IntuneTestState.Keys.ContainsKey("$Path") -or "$Path" -eq $global:IntuneTestState.Root } + Mock Get-ChildItem { + $prefix = $global:IntuneTestState.Root + '\' + $global:IntuneTestState.Keys.Keys | Where-Object { $_.StartsWith($prefix) -and ($_.Substring($prefix.Length) -notlike '*\*') } | ForEach-Object { + [PSCustomObject]@{ PSPath = $_; PSChildName = $_.Substring($prefix.Length) } + } + } + Mock Get-ItemProperty { + $k = "$Path" + if (-not $global:IntuneTestState.Keys.ContainsKey($k)) { return $null } + $o = [PSCustomObject]@{} + foreach ($name in $global:IntuneTestState.Keys[$k].Keys) { $o | Add-Member -NotePropertyName $name -NotePropertyValue $global:IntuneTestState.Keys[$k][$name] } + $o + } + Mock Get-ItemPropertyValue { throw 'Get-ItemPropertyValue must not be used: it throws on a missing value' } + Mock Get-Service { $global:IntuneTestState.Service } + } + AfterEach { Remove-Variable -Name IntuneTestState -Scope Global -ErrorAction SilentlyContinue } + + It 'does not crash on subkeys without ProviderID and exits 0 for an enrolled device (H1)' { + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath + $r.ExitCode | Should -Be 0 + $r.Output | Should -Match 'Device is enrolled in Intune' + $r.Output | Should -Match 'abcd-1234' + Should -Invoke Get-ItemPropertyValue -Times 0 -Exactly + } + + It 'exits 1 and says not enrolled when only the non-enrollment subkeys exist (no crash)' { + $global:IntuneTestState.Keys.Remove("$($script:Root)\11111111-2222") + $global:IntuneTestState.Keys.Remove("$($script:Root)\11111111-2222\DMClient\MS DM Server") + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath + $r.ExitCode | Should -Be 1 + $r.Output | Should -Match 'does not appear to be enrolled' + $r.Output | Should -Not -Match 'Failed to test Intune enrollment' + } + + It 'exits 1 when the Intune record exists but EnrollmentState is not 1' { + $global:IntuneTestState.Keys["$($script:Root)\11111111-2222"].EnrollmentState = 0 + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath + $r.ExitCode | Should -Be 1 + $r.Output | Should -Match 'EnrollmentState is not 1' + } + + It 'does not count a non-Intune MDM provider as Intune (the old *Microsoft* wildcard would)' { + $global:IntuneTestState.Keys["$($script:Root)\11111111-2222"].ProviderID = 'Microsoft Something Else' + (Invoke-ScriptUnderTest -Path $script:ScriptPath).ExitCode | Should -Be 1 + } + + It 'exits 1 when the Enrollments key does not exist' { + $global:IntuneTestState.Keys.Clear() + Mock Test-Path { $false } + $r = Invoke-ScriptUnderTest -Path $script:ScriptPath + $r.ExitCode | Should -Be 1 + $r.Output | Should -Match 'registry path not found' + } +} diff --git a/Tests/TestHelpers.ps1 b/Tests/TestHelpers.ps1 new file mode 100644 index 0000000..a317670 --- /dev/null +++ b/Tests/TestHelpers.ps1 @@ -0,0 +1,107 @@ +# Shared helpers for the Pester tests. Dot-source this file from a test's BeforeAll block. +# Pester 5 syntax. Works in Windows PowerShell 5.1 and PowerShell 7. + +$script:RepoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path + +function Get-RepoPath { + param([Parameter(Mandatory)][string]$RelativePath) + Join-Path $script:RepoRoot $RelativePath +} + +# Parse a script and return the source text of the named top-level or nested functions, +# so a test can define them without running the script body. +function Import-ScriptFunction { + param( + [Parameter(Mandatory)][string]$Path, + [Parameter(Mandatory)][string[]]$Name + ) + $tokens = $null; $errors = $null + $ast = [System.Management.Automation.Language.Parser]::ParseFile($Path, [ref]$tokens, [ref]$errors) + if ($errors -and $errors.Count -gt 0) { throw "Parse errors in ${Path}: $($errors[0].Message)" } + $found = $ast.FindAll({ param($n) $n -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $Name -contains $n.Name }, $true) + $missing = $Name | Where-Object { $_ -notin $found.Name } + if ($missing) { throw "Function(s) not found in ${Path}: $($missing -join ', ')" } + ($found | ForEach-Object { $_.Extent.Text }) -join "`n`n" +} + +function Test-IsElevated { + if ($env:OS -ne 'Windows_NT') { return $false } + ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) +} + +# Run a script file in the current session and return its exit code and combined output. +# A script's `exit N` ends only that script, so the code lands in $LASTEXITCODE. +# ErrorActionPreference is reset to Continue because Pester sets it to Stop inside tests, +# and the scripts under test rely on Write-Error not being terminating. +function Invoke-ScriptUnderTest { + param( + [Parameter(Mandatory)][string]$Path, + [hashtable]$Arguments = @{} + ) + $ErrorActionPreference = 'Continue' + $global:LASTEXITCODE = $null + $output = & $Path @Arguments *>&1 | ForEach-Object { "$_" } + # A script that ends without `exit` returns 0 to its caller, so report that as 0 + $code = if ($null -eq $global:LASTEXITCODE) { 0 } else { [int]$global:LASTEXITCODE } + [PSCustomObject]@{ ExitCode = $code; Output = ($output -join "`n") } +} + +# Safety net for tests that run scripts in an elevated shell. Every cmdlet that can change the machine +# gets an UNFILTERED default mock that throws, so a path the test forgot to mock fails loudly instead +# of touching the real registry, services or files. Tests then re-mock the few cmdlets they need. +# Call this from BeforeAll or BeforeEach in the test file itself. +$script:StateChangingCommands = @( + 'New-Item', 'New-ItemProperty', 'Set-ItemProperty', 'Remove-Item', 'Remove-ItemProperty', + 'Rename-Item', 'Copy-Item', 'Move-Item', 'Set-Service', 'Start-Service', 'Stop-Service', + 'Restart-Service', 'Start-Process', 'Stop-Process', 'Add-Content', 'Set-Content', 'Out-File', + 'Invoke-WebRequest', 'Invoke-RestMethod', 'Invoke-Expression', 'Import-Certificate' +) + +# Build an HTTP failure the way Invoke-RestMethod surfaces one: an exception with a Response whose +# StatusCode has a value__ member (the shape the retry code reads). +function New-HttpException { + param([int]$StatusCode, [string]$Message = "HTTP $StatusCode") + $ex = [System.Exception]::new($Message) + $ex | Add-Member -NotePropertyName Response -NotePropertyValue ([PSCustomObject]@{ + StatusCode = ([PSCustomObject]@{ value__ = $StatusCode }) + Headers = @{} + }) + $ex +} + +# Path to the shared module manifest +function Get-ModuleManifestPath { Get-RepoPath 'Common\IntuneCommon.psd1' } + +# Mock body for Invoke-RestMethod inside the IntuneCommon module. Routes live in $global:IntuneTestState.Routes +# as @{ Like = '*pattern*'; Body = } or @{ Like = ...; Throw = }. The first route whose +# Like matches the URI wins. An unmatched URI throws, so a script cannot reach a real endpoint by accident. +# Every call is recorded in $global:IntuneTestState.Calls. +$script:GraphMockBody = { + $global:IntuneTestState.Calls += [PSCustomObject]@{ Uri = "$Uri"; Method = "$Method"; Body = $Body } + foreach ($route in $global:IntuneTestState.Routes) { + if ("$Uri" -like $route.Like) { + if ($route.Throw) { throw $route.Throw } + return $route.Body + } + } + throw "UNEXPECTED URI in test: $Uri" +} + +# Fresh state for a Graph-backed script test. Token route is added first. +function New-GraphTestState { + @{ + Calls = @() + Routes = [System.Collections.ArrayList]@( + @{ Like = '*login.microsoftonline.com*/oauth2/v2.0/token'; Body = [PSCustomObject]@{ access_token = 'test-token' } } + ) + } +} + +function Add-GraphRoute { + param([string]$Like, $Body, $Throw, [switch]$First) + $r = @{ Like = $Like; Body = $Body; Throw = $Throw } + if ($First) { $global:IntuneTestState.Routes.Insert(0, $r) } else { [void]$global:IntuneTestState.Routes.Add($r) } +} + +# Wrap a list the way Graph does +function New-GraphPage { param($Items, [string]$NextLink) $o = [ordered]@{ value = @($Items) }; if ($NextLink) { $o['@odata.nextLink'] = $NextLink }; [PSCustomObject]$o } diff --git a/Troubleshooting/Get-IntuneDeviceLogs.ps1 b/Troubleshooting/Get-IntuneDeviceLogs.ps1 index 056b8bd..1aacb08 100644 --- a/Troubleshooting/Get-IntuneDeviceLogs.ps1 +++ b/Troubleshooting/Get-IntuneDeviceLogs.ps1 @@ -23,11 +23,15 @@ .EXAMPLE .\Get-IntuneDeviceLogs.ps1 -OutputPath 'C:\Logs\Intune' -IncludeEventLogs + The collected logs and the Enrollments registry export can contain device and user identifiers. + When the script creates the output folder it removes inherited permissions and grants access + to SYSTEM and Administrators only. A folder that already exists is left as it is. + .NOTES Requires: Administrator privileges Exit Codes: - - 0: Log collection successful - - 1: Log collection failed or error occurred + - 0: Every collection that was attempted succeeded + - 1: Any collection failed, nothing was collected, or an error occurred #> [CmdletBinding()] @@ -78,8 +82,15 @@ try # Create output directory if it doesn't exist # This ensures the directory exists before collecting logs if (-not (Test-Path -Path $OutputPath)) { - New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null + New-Item -Path $OutputPath -ItemType Directory -Force -ErrorAction Stop | Out-Null Write-Host "Created output directory: $OutputPath" -ForegroundColor Green + + # The folder holds device and user identifiers. Limit it to SYSTEM and Administrators. + # S-1-5-18 is SYSTEM and S-1-5-32-544 is Administrators, so this works on any display language. + icacls $OutputPath /inheritance:r /grant:r "*S-1-5-18:(OI)(CI)F" "*S-1-5-32-544:(OI)(CI)F" | Out-Null + if ($LASTEXITCODE -ne 0) { + throw "Could not restrict access to the output folder $OutputPath (icacls exit code $LASTEXITCODE)." + } } Write-Host "Output path: $OutputPath" -ForegroundColor Cyan @@ -172,10 +183,14 @@ try if (Get-Command reg -ErrorAction SilentlyContinue) { $regFile = Join-Path $regOutputPath "Enrollments.reg" reg export "HKLM\SOFTWARE\Microsoft\Enrollments" $regFile /y | Out-Null - if (Test-Path -Path $regFile) { + if ($LASTEXITCODE -eq 0 -and (Test-Path -Path $regFile)) { $collectedLogs += "Enrollment registry information" Write-Host " Successfully collected enrollment registry information." -ForegroundColor Green } + else { + $failedLogs += "Enrollment registry information: reg export failed (exit code $LASTEXITCODE)" + Write-Host " reg export failed (exit code $LASTEXITCODE)." -ForegroundColor Red + } } else { Write-Host " reg.exe not available. Skipping registry export." -ForegroundColor Yellow @@ -201,10 +216,11 @@ try # Export relevant event logs # These event logs contain Windows events related to Intune operations - $eventLogs = @("Microsoft-Windows-DeviceManagement-Enterprise-Diagnostics-Provider", - "Microsoft-Windows-User Device Registration/Admin", - "Microsoft-Windows-DeviceManagement-Enterprise-Diagnostics-Provider/Admin") - + $eventLogs = @("Microsoft-Windows-DeviceManagement-Enterprise-Diagnostics-Provider/Admin", + "Microsoft-Windows-DeviceManagement-Enterprise-Diagnostics-Provider/Operational", + "Microsoft-Windows-User Device Registration/Admin") + + $exportedEventLogs = @() if (Get-Command wevtutil -ErrorAction SilentlyContinue) { foreach ($logName in $eventLogs) { try { @@ -212,26 +228,41 @@ try if (Get-WinEvent -ListLog $logName -ErrorAction SilentlyContinue) { $logFileName = $logName -replace '[\\/]', '_' $logFile = Join-Path $eventLogOutputPath "$logFileName.evtx" - + # Export event log wevtutil epl $logName $logFile | Out-Null - if (Test-Path -Path $logFile) { + if ($LASTEXITCODE -eq 0 -and (Test-Path -Path $logFile)) { + $exportedEventLogs += $logName Write-Host " Exported event log: $logName" -ForegroundColor Green } + else { + $failedLogs += "Event log ${logName}: wevtutil exit code $LASTEXITCODE" + Write-Host " Could not export event log: $logName (wevtutil exit code $LASTEXITCODE)" -ForegroundColor Red + } + } + else { + Write-Host " Event log not present on this device: $logName" -ForegroundColor Yellow } } catch { Write-Verbose "Could not export event log: $logName - $($_.Exception.Message)" - Write-Host " Could not export event log: $logName" -ForegroundColor Yellow + $failedLogs += "Event log ${logName}: $($_.Exception.Message)" + Write-Host " Could not export event log: $logName" -ForegroundColor Red } } } else { Write-Host " wevtutil.exe not available. Skipping event log export." -ForegroundColor Yellow } - - $collectedLogs += "Windows Event Logs" - Write-Host " Successfully collected Windows Event Logs." -ForegroundColor Green + + # Only claim the event logs were collected when at least one was exported + if ($exportedEventLogs.Count -gt 0) { + $collectedLogs += "Windows Event Logs ($($exportedEventLogs.Count) exported)" + Write-Host " Collected $($exportedEventLogs.Count) Windows Event Log(s)." -ForegroundColor Green + } + else { + Write-Host " No Windows Event Logs were exported." -ForegroundColor Yellow + } } catch { $failedLogs += "Windows Event Logs: $($_.Exception.Message)" @@ -286,6 +317,17 @@ System Information: } } + # Failures were collected above; report them in the exit code so callers can tell + if ($failedLogs.Count -gt 0) { + Write-Error "Log collection completed with $($failedLogs.Count) failure(s). See the summary above and LogCollectionSummary.txt in $OutputPath." + exit 1 + } + if ($collectedLogs.Count -le 1) { + # Only the summary file exists: no log source was found at all + Write-Error "No Intune logs were found on this device. Only the summary was written to $OutputPath." + exit 1 + } + Write-Host "`nLog collection completed successfully." -ForegroundColor Green exit 0 } diff --git a/Troubleshooting/Start-MDMSync.ps1 b/Troubleshooting/Start-MDMSync.ps1 index 87225f0..21d2825 100644 --- a/Troubleshooting/Start-MDMSync.ps1 +++ b/Troubleshooting/Start-MDMSync.ps1 @@ -1,3 +1,6 @@ +#Requires -Version 5.1 +#Requires -PSEdition Desktop + <# .SYNOPSIS Starts an MDM sync session using Windows Management APIs. @@ -8,6 +11,13 @@ and the MDM service (e.g., Microsoft Intune). The script waits up to the specified timeout for the sync to complete and provides status updates during the process. + The WinRT type this script uses can only be loaded by Windows PowerShell 5.1. PowerShell 7 cannot + load it, so the script requires the Desktop edition and says so, instead of failing on the type load. + + A session that reaches Completed with an extended error code is reported as a failure. + The session's own ExtendedError is read; the states are NotStarted, Starting, Connecting, + Communicating, AlertStatusAvailable, Retrying and Completed. + .PARAMETER TimeoutSeconds Optional. Maximum time in seconds to wait for sync to complete. Default is 60 seconds. @@ -21,104 +31,123 @@ .\Start-MDMSync.ps1 -TimeoutSeconds 120 -CheckIntervalSeconds 10 .NOTES - Requires: Windows 10/11 with MDM enrollment + Requires: Windows PowerShell 5.1 (Desktop edition), Windows 10/11 with MDM enrollment Exit Codes: - - 0: Sync completed successfully - - 1: Sync failed or ended with error state + - 0: Sync completed with no error + - 1: Sync failed (session could not be created, or it completed with an error) or an error occurred - 2: Sync timeout (didn't complete within timeout period) #> [CmdletBinding()] param( [Parameter(Mandatory=$false)] + [ValidateRange(1, 3600)] [int]$TimeoutSeconds = 60, - + [Parameter(Mandatory=$false)] + [ValidateRange(1, 300)] [int]$CheckIntervalSeconds = 5 ) +# Create the WinRT MDM session. Kept in a function so a test can replace it. +function Get-MdmSession { + [CmdletBinding()] + param() + + # Loads the Windows.Management.MdmSessionManager type from the Windows Runtime + [Windows.Management.MdmSessionManager, Windows.Management, ContentType = WindowsRuntime] | Out-Null + return [Windows.Management.MdmSessionManager]::TryCreateSession() +} + +# Return the session's extended error as text (for example 0x80190190), or $null when there is none. +# ExtendedError is an HRESULT projected as an Exception; S_OK (0) means no error. +function Get-MdmSessionError { + [CmdletBinding()] + param( + [Parameter(Mandatory=$true)] + $Session + ) + + $extended = $Session.ExtendedError + if ($null -eq $extended) { return $null } + + $hresult = if ($extended -is [System.Exception]) { [int]$extended.HResult } else { [int]$extended } + if ($hresult -eq 0) { return $null } + return ('0x{0:X8}' -f $hresult) +} + +# Poll the session until it is Completed or the timeout is reached. No early exit on an unchanged +# state: a sync that sits in Connecting is slow, not failed, and the timeout covers it. +# Returns the final state, the extended error text (or $null) and whether the timeout was reached. +function Wait-MdmSession { + [CmdletBinding()] + param( + [Parameter(Mandatory=$true)] + $Session, + + [Parameter(Mandatory=$true)] + [int]$TimeoutSeconds, + + [Parameter(Mandatory=$true)] + [int]$CheckIntervalSeconds + ) + + $maxIterations = [math]::Ceiling($TimeoutSeconds / $CheckIntervalSeconds) + $iteration = 0 + + do { + Start-Sleep -Seconds $CheckIntervalSeconds + $iteration++ + Write-Host "Waiting for sync to complete... ($($iteration * $CheckIntervalSeconds)/$TimeoutSeconds seconds) - State: $($Session.State)" -ForegroundColor Cyan + } while (("$($Session.State)" -ne "Completed") -and ($iteration -lt $maxIterations)) + + [PSCustomObject]@{ + State = "$($Session.State)" + Error = Get-MdmSessionError -Session $Session + TimedOut = ("$($Session.State)" -ne "Completed") + } +} + +# Map a wait result to the documented exit code: 0 success, 1 failure, 2 timeout. +function Get-MdmSyncExitCode { + [CmdletBinding()] + param( + [Parameter(Mandatory=$true)] + $Result + ) + + if ($Result.TimedOut) { return 2 } + if ($Result.Error) { return 1 } + return 0 +} + # Main script execution wrapped in try-catch for error handling try { - # Load the Windows.Management.MdmSessionManager type from Windows Runtime - # This API is used to create and manage MDM sync sessions - # Out-Null suppresses the output from the type loading - [Windows.Management.MdmSessionManager, Windows.Management, ContentType = WindowsRuntime] | Out-Null - - # Attempt to create a new MDM sync session - # TryCreateSession() returns a session object if successful, or null if it fails Write-Host "Attempting to create MDM sync session..." -ForegroundColor Yellow - $MDMSession = [Windows.Management.MdmSessionManager]::TryCreateSession() - - # Validate that the session was created successfully - # If null, the device may not be enrolled in MDM or there's a configuration issue + $MDMSession = Get-MdmSession + + # TryCreateSession returns null when the device is not enrolled or MDM is not configured if ($null -eq $MDMSession) { Write-Error "Failed to create MDM session. Device may not be enrolled in MDM." exit 1 } - # Start the MDM sync session asynchronously - # StartAsync() initiates the sync process but doesn't wait for completion + # StartAsync() initiates the sync but doesn't wait for completion Write-Host "MDM session created. Starting sync..." -ForegroundColor Yellow $MDMSession.StartAsync() | Out-Null - # Wait for sync to complete with timeout protection - # Calculate maximum number of iterations based on timeout and check interval - $maxIterations = [math]::Ceiling($TimeoutSeconds / $CheckIntervalSeconds) - $MDMSyncTimeout = 0 # Counter for iterations - $lastState = $null - $unchangedCount = 0 + $result = Wait-MdmSession -Session $MDMSession -TimeoutSeconds $TimeoutSeconds -CheckIntervalSeconds $CheckIntervalSeconds + $exitCode = Get-MdmSyncExitCode -Result $result - # Loop until sync completes or timeout is reached - # Check session state at specified intervals - do { - # Wait for the specified interval before checking status again - Start-Sleep -Seconds $CheckIntervalSeconds - # Increment the iteration counter - $MDMSyncTimeout += 1 - - # Check if session state has changed - if ($MDMSession.State -eq $lastState) { - $unchangedCount++ - if ($unchangedCount -gt 5) { - Write-Warning "Session state unchanged for extended period. Current state: $($MDMSession.State)" - break - } - } - else { - $unchangedCount = 0 - } - $lastState = $MDMSession.State - - # Display progress to the user - Write-Host "Waiting for sync to complete... ($($MDMSyncTimeout * $CheckIntervalSeconds)/$TimeoutSeconds seconds) - State: $($MDMSession.State)" -ForegroundColor Cyan - } while (($MDMSession.State -ne "Completed") -and ($MDMSyncTimeout -lt $maxIterations)) - - # Check the final status of the sync session - if ($MDMSession.State -eq "Completed") { - # Sync completed successfully - Write-Host "MDM sync completed successfully." -ForegroundColor Green - exit 0 - } - elseif ($MDMSession.State -eq "Error" -or $MDMSession.State -eq "Failed") { - # Sync ended in an explicit error state - Write-Error "MDM sync failed with state: $($MDMSession.State)" - exit 1 - } - elseif ($MDMSyncTimeout -ge $maxIterations) { - # Sync did not complete within the timeout period - # This may indicate network issues or MDM service problems - Write-Warning "MDM sync did not complete within the timeout period. Current state: $($MDMSession.State)" - exit 2 - } - else { - # Sync ended in an unexpected state (not Completed, Error, Failed, or timeout) - Write-Warning "MDM sync ended with unexpected state: $($MDMSession.State)" - exit 1 + switch ($exitCode) { + 0 { Write-Host "MDM sync completed successfully." -ForegroundColor Green } + 1 { Write-Error "MDM sync completed with error $($result.Error) (state: $($result.State))." } + 2 { Write-Warning "MDM sync did not complete within $TimeoutSeconds seconds. Current state: $($result.State)$(if ($result.Error) { ", extended error $($result.Error)" })" } } + exit $exitCode } # Error handling block - catches exceptions during session creation or sync process catch { - # Display the error message with script name for context Write-Error "Start-MDMSync: Failed to start MDM sync - $($_.Exception.Message)" if ($PSBoundParameters.ContainsKey('Verbose')) { Write-Verbose "Stack Trace: $($_.ScriptStackTrace)" diff --git a/Troubleshooting/Test-IntuneConnectivity.ps1 b/Troubleshooting/Test-IntuneConnectivity.ps1 index 10605aa..0f43f3c 100644 --- a/Troubleshooting/Test-IntuneConnectivity.ps1 +++ b/Troubleshooting/Test-IntuneConnectivity.ps1 @@ -1,585 +1,588 @@ -<# -.SYNOPSIS - Tests connectivity to Microsoft Intune and Microsoft 365 endpoints required for Intune management. - -.DESCRIPTION - This script tests connectivity to all mandatory Intune and Microsoft 365 Common endpoints - required for Intune device management functionality. It queries Microsoft's Office 365 IP - Address and URL web service to obtain the latest endpoint URLs for Service Area "MEM" - (Microsoft Endpoint Manager) and "M365 Common", then tests connectivity to those endpoints - from the client device. The script handles proxy configurations and provides detailed - output about which endpoints are accessible. - -.PARAMETER ExportPath - Optional path to export test results to a JSON file. - If specified, test results including network configuration and endpoint status will be saved. - -.EXAMPLE - .\Test-IntuneConnectivity.ps1 - -.EXAMPLE - .\Test-IntuneConnectivity.ps1 -ExportPath "C:\Temp\ConnectivityTest.json" - -.NOTES - Prerequisites: - - PowerShell 3.0 or later - - PS script execution policy: Bypass (or appropriate policy to allow script execution) - - Does not require elevation (runs with current user permissions) - - Internet connectivity to reach Microsoft endpoints - - The script: - - Queries Microsoft's endpoint web service for the latest endpoint URLs - - Tests connectivity to mandatory Intune and M365 Common endpoints - - Handles proxy configurations automatically - - Displays network configuration information for troubleshooting - - Returns $true if all mandatory endpoints are accessible, $false otherwise -#> - -[CmdletBinding()] -param( - [Parameter(Mandatory=$false)] - [string]$ExportPath -) - -Function Get-ProxySettings { - <# - .SYNOPSIS - Retrieves the current Windows HTTP proxy configuration. - - .DESCRIPTION - This function checks the system's winHTTP proxy settings using netsh command. - It determines if the system is using a proxy server or has direct internet access. - Returns the proxy server address or "NoProxy" if direct access is configured. - - .OUTPUTS - String: Proxy server address (with http:// prefix) or "NoProxy" - #> - - # Display status message to user - Write-Host "Checking winHTTP proxy settings..." -ForegroundColor Yellow - - # Initialize proxy server variable with default value - $ProxyServer = "NoProxy" - - # Execute netsh command to retrieve winHTTP proxy configuration - # This command shows the current proxy settings for Windows HTTP services - $winHTTP = netsh winhttp show proxy - - # Parse the output to find the proxy server line - # Select-String searches for lines containing "server" (case-insensitive) - $Proxy = $winHTTP | Select-String server - - # Extract the proxy server address from the output - # TrimStart removes the "Proxy Server(s) : " prefix to get just the address - $ProxyServer = $Proxy.ToString().TrimStart("Proxy Server(s) : ") - - # Check if the output indicates direct access (no proxy configured) - if ($ProxyServer -eq "Direct access (no proxy server).") { - # Set to "NoProxy" to indicate direct internet access - $ProxyServer = "NoProxy" - Write-Host "Access Type : DIRECT" - } - - # Check if a proxy server is configured and ensure it has http:// prefix - # This is required for the Invoke-WebRequest cmdlet to use the proxy correctly - if ( ($ProxyServer -ne "NoProxy") -and (-not($ProxyServer.StartsWith("http://")))) { - # Display proxy configuration to user - Write-Host "Access Type : PROXY" - Write-Host "Proxy Server List :" $ProxyServer - # Add http:// prefix if not present (required for proxy usage) - $ProxyServer = "http://" + $ProxyServer - } - - # Return the proxy server address or "NoProxy" - return $ProxyServer -} - -Function Get-M365CommonEndpointList { - <# - .SYNOPSIS - Retrieves the list of Microsoft 365 Common endpoints required for Intune connectivity. - - .DESCRIPTION - This function queries Microsoft's Office 365 IP Address and URL web service to get - the latest list of M365 Common endpoints. These endpoints are required for various - Microsoft 365 services to function properly. The function filters and processes - the endpoint data for connectivity testing. - - .OUTPUTS - Array: Processed endpoint list with category and URL information - #> - - # Function to invoke endpoint API with retry logic - # Handles transient failures (429, 503, etc.) with exponential backoff - function Invoke-EndpointApiWithRetry { - [CmdletBinding()] - param( - [Parameter(Mandatory=$true)] - [string]$Uri, - - [Parameter(Mandatory=$false)] - [int]$MaxRetries = 3, - - [Parameter(Mandatory=$false)] - [int]$InitialDelaySeconds = 2 - ) - - $retryCount = 0 - $delaySeconds = $InitialDelaySeconds - - while ($retryCount -le $MaxRetries) { - try { - $response = Invoke-RestMethod -Uri $Uri -ErrorAction Stop - return $response - } - catch { - $statusCode = $_.Exception.Response.StatusCode.value__ - - # Check if this is a retryable error (429 Too Many Requests, 503 Service Unavailable, 502 Bad Gateway, 504 Gateway Timeout) - if ($statusCode -in @(429, 502, 503, 504) -and $retryCount -lt $MaxRetries) { - $retryCount++ - Write-Verbose "Endpoint API call failed with status $statusCode. Retrying in $delaySeconds seconds (attempt $retryCount of $MaxRetries)..." - Start-Sleep -Seconds $delaySeconds - # Exponential backoff: double the delay for next retry - $delaySeconds = $delaySeconds * 2 - } - else { - # Not a retryable error or max retries reached - throw - } - } - } - } - - # Query Microsoft's Office 365 endpoint web service for Common service area endpoints - # The service provides up-to-date endpoint URLs that may change over time - # ServiceAreas=Common: Requests endpoints for common M365 services - # clientrequestid: Unique GUID for tracking the request - try { - $endpointListM365 = (Invoke-EndpointApiWithRetry -Uri ("https://endpoints.office.com/endpoints/WorldWide?ServiceAreas=Common`&clientrequestid=" + ([GUID]::NewGuid()).Guid)) | Where-Object { $_.ServiceArea -eq "Common" -and $_.urls } - } - catch { - Write-Error "Get-M365CommonEndpointList: Failed to retrieve M365 Common endpoints - $($_.Exception.Message)" - return @() - } - - # Create a mapping of endpoint IDs to human-readable categories - # This helps identify what each endpoint is used for during testing - # mandatory = $true indicates these endpoints are required for Intune to function - [PsObject[]]$endpointListCategoriesM365 = @() - $endpointListCategoriesM365 += [PsObject]@{id = 56; category = 'M365 Common'; mandatory = $true } - $endpointListCategoriesM365 += [PsObject]@{id = 59; category = 'M365 Common'; mandatory = $true } - $endpointListCategoriesM365 += [PsObject]@{id = 78; category = 'M365 Common'; mandatory = $true } - $endpointListCategoriesM365 += [PsObject]@{id = 83; category = 'M365 Common'; mandatory = $true } - $endpointListCategoriesM365 += [PsObject]@{id = 84; category = 'M365 Common'; mandatory = $true } - $endpointListCategoriesM365 += [PsObject]@{id = 125; category = 'M365 Common'; mandatory = $true } - $endpointListCategoriesM365 += [PsObject]@{id = 156; category = 'M365 Common'; mandatory = $true } - - # Process the endpoint list and create a structured output object - # This combines endpoint data with category information for easier processing - [PsObject[]]$endpointRequestListM365 = @() - for ($i = 0; $i -lt $endpointListM365.Count; $i++) { - # Match each endpoint with its category based on ID - # Create an object with id, category, urls, and mandatory flag - $endpointRequestListM365 += [PsObject]@{ id = $endpointListM365[$i].id; category = ($endpointListCategoriesM365 | Where-Object { $_.id -eq $endpointListM365[$i].id }).category; urls = $endpointListM365[$i].urls; mandatory = ($endpointListCategoriesM365 | Where-Object { $_.id -eq $endpointListM365[$i].id }).mandatory } - } - - # Clean up URL list: Remove wildcard prefixes and ensure uniqueness - # Wildcard prefixes (*.) are not useful for direct connectivity testing - for ($i = 0; $i -lt $endpointRequestListM365.Count; $i++) { - for ($j = 0; $j -lt $endpointRequestListM365[$i].urls.Count; $j++) { - # Remove *. prefix from URLs (e.g., "*.example.com" becomes "example.com") - $targetUrl = $endpointRequestListM365[$i].urls[$j].replace('*.', '') - $endpointRequestListM365[$i].urls[$j] = $targetUrl - } - # Remove duplicate URLs and sort alphabetically for consistency - $endpointRequestListM365[$i].urls = $endpointRequestListM365[$i].urls | Sort-Object -Unique - } - - # Return the processed endpoint list - return $endpointRequestListM365 -} - -Function Get-IntuneEndpointList { - <# - .SYNOPSIS - Retrieves the list of Microsoft Endpoint Manager (Intune) endpoints required for connectivity. - - .DESCRIPTION - This function queries Microsoft's Office 365 IP Address and URL web service to get - the latest list of MEM (Microsoft Endpoint Manager) endpoints. These endpoints are - specifically required for Intune device management functionality. The function - filters and processes the endpoint data for connectivity testing. - - .OUTPUTS - Array: Processed endpoint list with category and URL information - #> - - # Query Microsoft's Office 365 endpoint web service for MEM (Microsoft Endpoint Manager) service area endpoints - # ServiceAreas=MEM: Requests endpoints specifically for Intune/MEM services - # clientrequestid: Unique GUID for tracking the request - try { - $endpointList = (Invoke-EndpointApiWithRetry -Uri ("https://endpoints.office.com/endpoints/WorldWide?ServiceAreas=MEM`&clientrequestid=" + ([GUID]::NewGuid()).Guid)) | Where-Object { $_.ServiceArea -eq "MEM" -and $_.urls } - } - catch { - Write-Error "Get-IntuneEndpointList: Failed to retrieve Intune endpoints - $($_.Exception.Message)" - return @() - } - - # Create a mapping of endpoint IDs to human-readable categories - # mandatory = $true: Endpoints required for basic Intune functionality - # mandatory = $false: Optional endpoints (e.g., platform-specific or feature-specific) - [PsObject[]]$endpointListCategories = @() - $endpointListCategories += [PsObject]@{id = 163; category = 'Global'; mandatory = $true } - $endpointListCategories += [PsObject]@{id = 164; category = 'Delivery Optimization'; mandatory = $true } - $endpointListCategories += [PsObject]@{id = 165; category = 'NTP Sync'; mandatory = $true } - $endpointListCategories += [PsObject]@{id = 169; category = 'Windows Notifications & Store'; mandatory = $true } - $endpointListCategories += [PsObject]@{id = 170; category = 'Scripts & Win32 Apps'; mandatory = $true } - $endpointListCategories += [PsObject]@{id = 171; category = 'Push Notifications'; mandatory = $true } - $endpointListCategories += [PsObject]@{id = 172; category = 'Delivery Optimization'; mandatory = $true } - $endpointListCategories += [PsObject]@{id = 173; category = 'Autopilot Self-deploy'; mandatory = $true } - $endpointListCategories += [PsObject]@{id = 178; category = 'Apple Device Management'; mandatory = $false } - $endpointListCategories += [PsObject]@{id = 179; category = 'Android (AOSP) Device Management'; mandatory = $false } - $endpointListCategories += [PsObject]@{id = 181; category = 'Remote Help'; mandatory = $false } - $endpointListCategories += [PsObject]@{id = 182; category = 'Collect Diagnostics'; mandatory = $true } - $endpointListCategories += [PsObject]@{id = 186; category = 'Microsoft Azure attestation - Windows 11 only'; mandatory = $true } - $endpointListCategories += [PsObject]@{id = 187; category = 'Android Remote Help'; mandatory = $false } - $endpointListCategories += [PsObject]@{id = 188; category = 'Remote Help GCC Dependency'; mandatory = $false } - $endpointListCategories += [PsObject]@{id = 189; category = 'Feature Flighting'; mandatory = $false } - - # Process the endpoint list and create a structured output object - # This combines endpoint data with category information for easier processing - [PsObject[]]$endpointRequestList = @() - for ($i = 0; $i -lt $endpointList.Count; $i++) { - # Match each endpoint with its category based on ID - # Create an object with id, category, urls, and mandatory flag - $endpointRequestList += [PsObject]@{ id = $endpointList[$i].id; category = ($endpointListCategories | Where-Object { $_.id -eq $endpointList[$i].id }).category; urls = $endpointList[$i].urls; mandatory = ($endpointListCategories | Where-Object { $_.id -eq $endpointList[$i].id }).mandatory } - } - - # Clean up URL list: Remove wildcard prefixes and ensure uniqueness - # Wildcard prefixes (*.) are not useful for direct connectivity testing - for ($i = 0; $i -lt $endpointRequestList.Count; $i++) { - for ($j = 0; $j -lt $endpointRequestList[$i].urls.Count; $j++) { - # Remove *. prefix from URLs (e.g., "*.example.com" becomes "example.com") - $targetUrl = $endpointRequestList[$i].urls[$j].replace('*.', '') - $endpointRequestList[$i].urls[$j] = $targetUrl - } - # Remove duplicate URLs and sort alphabetically for consistency - $endpointRequestList[$i].urls = $endpointRequestList[$i].urls | Sort-Object -Unique - } - - # Return the processed endpoint list - return $endpointRequestList -} - -Function Test-DeviceIntuneConnectivity { - <# - .SYNOPSIS - Tests connectivity to all required Intune and Microsoft 365 endpoints. - - .DESCRIPTION - This function tests connectivity to mandatory Intune and M365 Common endpoints - from the device. It checks each endpoint using HTTP requests and reports - success or failure. The function handles proxy configurations and provides - detailed output about which endpoints are accessible. - - .OUTPUTS - Boolean: $true if all mandatory endpoints are accessible, $false otherwise - #> - - # Store the original error action preference to restore it later - # This prevents the function from permanently changing the global error handling behavior - $originalErrorAction = $ErrorActionPreference - - # Set error action to SilentlyContinue to prevent errors from stopping the test - # This allows the script to continue testing other endpoints even if some fail - $ErrorActionPreference = 'SilentlyContinue' - - # Initialize variables for tracking test results - $TestFailed = $false # Flag to track if any mandatory endpoint failed - $ProxyServer = Get-ProxySettings # Get proxy configuration - $endpointListM365Common = Get-M365CommonEndpointList # Get M365 Common endpoints - $endpointListIntune = Get-IntuneEndpointList # Get Intune-specific endpoints - $script:failedEndpointList = @{} # Hash table to store failed endpoints by category (script-level for export) - $script:passedEndpointList = @{} # Hash table to store passed endpoints by category (script-level for export) - - # Validate that endpoints were retrieved successfully - if ($null -eq $endpointListM365Common -or $endpointListM365Common.Count -eq 0) { - Write-Warning "No M365 Common endpoints retrieved. Connectivity test may be incomplete." - } - if ($null -eq $endpointListIntune -or $endpointListIntune.Count -eq 0) { - Write-Warning "No Intune endpoints retrieved. Connectivity test may be incomplete." - } - if (($null -eq $endpointListM365Common -or $endpointListM365Common.Count -eq 0) -and - ($null -eq $endpointListIntune -or $endpointListIntune.Count -eq 0)) { - Write-Error "Failed to retrieve any endpoints. Cannot proceed with connectivity test." - return $false - } - - # Display start message to user - Write-Host "Starting Connectivity Check..." -ForegroundColor Yellow - - # Test M365 Common endpoints (required for various M365 services) - foreach ($endpoint in $endpointListM365Common) - { - # Only test mandatory endpoints (skip optional ones) - if ($endpoint.mandatory -eq $true) - { - # Display the category being tested - Write-Host "Checking Category: ..." $endpoint.category -ForegroundColor Yellow - - # Test each URL in the endpoint category - foreach ($url in $endpoint.urls) { - # Test connectivity based on proxy configuration - try { - if ($ProxyServer -eq "NoProxy") - { - # Direct connection (no proxy) - test endpoint directly - # -UseBasicParsing: Faster, doesn't parse HTML (we only need status code) - # -TimeoutSec: Set timeout to prevent hanging - $TestResult = (Invoke-WebRequest -uri $url -UseBasicParsing -TimeoutSec 10 -ErrorAction Stop).StatusCode - } - else - { - # Proxy connection - test endpoint through proxy server - $TestResult = (Invoke-WebRequest -uri $url -UseBasicParsing -Proxy $ProxyServer -TimeoutSec 10 -ErrorAction Stop).StatusCode - } - } - catch { - # Connection failed - set TestResult to indicate failure - $TestResult = $null - } - - # Check if the connection was successful (HTTP 200 = OK) - # Also check if TestResult is null (connection failed) - if ($TestResult -eq 200) - { - # Track passed endpoints for export - if (-not $script:passedEndpointList.ContainsKey($endpoint.category)) { - $script:passedEndpointList.Add($endpoint.category, @()) - } - $script:passedEndpointList[$endpoint.category] += $url - - if (($url.StartsWith('approdimedata') -or ($url.StartsWith("intunemaape13") -or $url.StartsWith("intunemaape17") -or $url.StartsWith("intunemaape18") -or $url.StartsWith("intunemaape19")))) { - Write-Host "Connection to " $url ".............. Succeeded (needed for Asia & Pacific tenants only)." -ForegroundColor Green - } - elseif (($url.StartsWith('euprodimedata') -or ($url.StartsWith("intunemaape7") -or $url.StartsWith("intunemaape8") -or $url.StartsWith("intunemaape9") -or $url.StartsWith("intunemaape10") -or $url.StartsWith("intunemaape11") -or $url.StartsWith("intunemaape12")))) { - Write-Host "Connection to " $url ".............. Succeeded (needed for Europe tenants only)." -ForegroundColor Green - } - elseif (($url.StartsWith('naprodimedata') -or ($url.StartsWith("intunemaape1") -or $url.StartsWith("intunemaape2") -or $url.StartsWith("intunemaape3") -or $url.StartsWith("intunemaape4") -or $url.StartsWith("intunemaape5") -or $url.StartsWith("intunemaape6")))) { - Write-Host "Connection to " $url ".............. Succeeded (needed for North America tenants only)." -ForegroundColor Green - } - else { - Write-Host "Connection to " $url ".............. Succeeded." -ForegroundColor Green - } - } - else - { - # Connection failed - mark test as failed and record the failed endpoint - # TestResult is either null (exception) or not 200 (non-success status) - $TestFailed = $true - - # Add failed endpoint to the failed list by category - # This groups failures by category for easier troubleshooting - if ($script:failedEndpointList.ContainsKey($endpoint.category)) { - # Category already exists - add URL to existing array - $script:failedEndpointList[$endpoint.category] += $url - } - else { - # New category - create new entry with URL - $script:failedEndpointList.Add($endpoint.category, @($url)) - } - if (($url.StartsWith('approdimedata') -or ($url.StartsWith("intunemaape13") -or $url.StartsWith("intunemaape17") -or $url.StartsWith("intunemaape18") -or $url.StartsWith("intunemaape19")))) { - Write-Host "Connection to " $url ".............. Failed (needed for Asia & Pacific tenants only)." -ForegroundColor Red - } - elseif (($url.StartsWith('euprodimedata') -or ($url.StartsWith("intunemaape7") -or $url.StartsWith("intunemaape8") -or $url.StartsWith("intunemaape9") -or $url.StartsWith("intunemaape10") -or $url.StartsWith("intunemaape11") -or $url.StartsWith("intunemaape12")))) { - Write-Host "Connection to " $url ".............. Failed (needed for Europe tenants only)." -ForegroundColor Red - } - elseif (($url.StartsWith('naprodimedata') -or ($url.StartsWith("intunemaape1") -or $url.StartsWith("intunemaape2") -or $url.StartsWith("intunemaape3") -or $url.StartsWith("intunemaape4") -or $url.StartsWith("intunemaape5") -or $url.StartsWith("intunemaape6")))) { - Write-Host "Connection to " $url ".............. Failed (needed for North America tenants only)." -ForegroundColor Red - } - else { - Write-Host "Connection to " $url ".............. Failed." -ForegroundColor Red - } - } - } - } - else - { - #Write-Host "Skipping Category: ..." $endpoint.category -ForegroundColor Yellow - } - } - - foreach ($endpoint in $endpointListIntune) - { - if ($endpoint.mandatory -eq $true) - { - Write-Host "Checking Category: ..." $endpoint.category -ForegroundColor Yellow - foreach ($url in $endpoint.urls) { - try { - if ($ProxyServer -eq "NoProxy") { - $TestResult = (Invoke-WebRequest -uri $url -UseBasicParsing -TimeoutSec 10 -ErrorAction Stop).StatusCode - } - else { - $TestResult = (Invoke-WebRequest -uri $url -UseBasicParsing -Proxy $ProxyServer -TimeoutSec 10 -ErrorAction Stop).StatusCode - } - } - catch { - $TestResult = $null - } - if ($TestResult -eq 200) { - # Track passed endpoints for export - if (-not $script:passedEndpointList.ContainsKey($endpoint.category)) { - $script:passedEndpointList.Add($endpoint.category, @()) - } - $script:passedEndpointList[$endpoint.category] += $url - - if (($url.StartsWith('approdimedata') -or ($url.StartsWith("intunemaape13") -or $url.StartsWith("intunemaape17") -or $url.StartsWith("intunemaape18") -or $url.StartsWith("intunemaape19")))) { - Write-Host "Connection to " $url ".............. Succeeded (needed for Asia & Pacific tenants only)." -ForegroundColor Green - } - elseif (($url.StartsWith('euprodimedata') -or ($url.StartsWith("intunemaape7") -or $url.StartsWith("intunemaape8") -or $url.StartsWith("intunemaape9") -or $url.StartsWith("intunemaape10") -or $url.StartsWith("intunemaape11") -or $url.StartsWith("intunemaape12")))) { - Write-Host "Connection to " $url ".............. Succeeded (needed for Europe tenants only)." -ForegroundColor Green - } - elseif (($url.StartsWith('naprodimedata') -or ($url.StartsWith("intunemaape1") -or $url.StartsWith("intunemaape2") -or $url.StartsWith("intunemaape3") -or $url.StartsWith("intunemaape4") -or $url.StartsWith("intunemaape5") -or $url.StartsWith("intunemaape6")))) { - Write-Host "Connection to " $url ".............. Succeeded (needed for North America tenants only)." -ForegroundColor Green - } - else { - Write-Host "Connection to " $url ".............. Succeeded." -ForegroundColor Green - } - } - else { - # Connection failed - TestResult is either null (exception) or not 200 - $TestFailed = $true - if ($script:failedEndpointList.ContainsKey($endpoint.category)) { - $script:failedEndpointList[$endpoint.category] += $url - } - else { - $script:failedEndpointList.Add($endpoint.category, @($url)) - } - if (($url.StartsWith('approdimedata') -or ($url.StartsWith("intunemaape13") -or $url.StartsWith("intunemaape17") -or $url.StartsWith("intunemaape18") -or $url.StartsWith("intunemaape19")))) { - Write-Host "Connection to " $url ".............. Failed (needed for Asia & Pacific tenants only)." -ForegroundColor Red - } - elseif (($url.StartsWith('euprodimedata') -or ($url.StartsWith("intunemaape7") -or $url.StartsWith("intunemaape8") -or $url.StartsWith("intunemaape9") -or $url.StartsWith("intunemaape10") -or $url.StartsWith("intunemaape11") -or $url.StartsWith("intunemaape12")))) { - Write-Host "Connection to " $url ".............. Failed (needed for Europe tenants only)." -ForegroundColor Red - } - elseif (($url.StartsWith('naprodimedata') -or ($url.StartsWith("intunemaape1") -or $url.StartsWith("intunemaape2") -or $url.StartsWith("intunemaape3") -or $url.StartsWith("intunemaape4") -or $url.StartsWith("intunemaape5") -or $url.StartsWith("intunemaape6")))) { - Write-Host "Connection to " $url ".............. Failed (needed for North America tenants only)." -ForegroundColor Red - } - else { - Write-Host "Connection to " $url ".............. Failed." -ForegroundColor Red - } - } - } - } - else - { - #Write-Host "Skipping Category: ..." $endpoint.category -ForegroundColor Yellow - } - } - - # Summary: Display failed endpoints if any failures occurred - if ($TestFailed) - { - # Display summary of failed endpoints grouped by category - Write-Host "Test failed. Please check the following URLs:" -ForegroundColor Red - foreach ($failedEndpoint in $script:failedEndpointList.Keys) { - # Display category name - Write-Host $failedEndpoint -ForegroundColor Red - # Display each failed URL in that category - foreach ($failedUrl in $script:failedEndpointList[$failedEndpoint]) { - Write-Host $failedUrl -ForegroundColor Red - } - } - } - - # Restore the original error action preference - # This ensures the function doesn't permanently change error handling behavior - $ErrorActionPreference = $originalErrorAction - - # Return test result: $true if all mandatory endpoints passed, $false if any failed - if ($TestFailed) { - Write-Host "Test-DeviceIntuneConnectivity completed with failures." -ForegroundColor Yellow -BackgroundColor Black - return $false - } - else { - Write-Host "Test-DeviceIntuneConnectivity completed successfully." -ForegroundColor Green -BackgroundColor Black - return $true - } -} - -### Main Execution Section ### - -# Execute the connectivity test function -# This tests all mandatory Intune and M365 Common endpoints -$connectivityResult = Test-DeviceIntuneConnectivity - -# Display network configuration information -# This helps troubleshoot connectivity issues by showing the device's network setup -$NetworkConfiguration = @() - -# Get network configuration for all network interfaces -# This includes IP addresses, gateways, DNS servers, and network profiles -Get-NetIPConfiguration | ForEach-Object { - # Create a custom object with network configuration details - # Handle null values gracefully to prevent errors - $NetworkConfiguration += New-Object PSObject -Property @{ - InterfaceAlias = $_.InterfaceAlias # Network adapter name - ProfileName = if($null -ne $_.NetProfile.Name){$_.NetProfile.Name}else{""} # Network profile (Domain/Private/Public) - IPv4Address = if($null -ne $_.IPv4Address){$_.IPv4Address}else{""} # IPv4 address - IPv6Address = if($null -ne $_.IPv6Address){$_.IPv6Address}else{""} # IPv6 address - IPv4DefaultGateway = if($null -ne $_.IPv4DefaultGateway){$_.IPv4DefaultGateway.NextHop}else{""} # IPv4 gateway - IPv6DefaultGateway = if($null -ne $_.IPv6DefaultGateway){$_.IPv6DefaultGateway.NextHop}else{""} # IPv6 gateway - DNSServer = if($null -ne $_.DNSServer){$_.DNSServer.ServerAddresses}else{""} # DNS server addresses - } -} - -# Display the network configuration in a formatted table -# This provides a clear view of the device's network setup for troubleshooting -$NetworkConfiguration | Format-Table -AutoSize - -# Export results to file if path is specified -if ($ExportPath) { - try { - # Create directory if it doesn't exist - $exportDirectory = Split-Path -Path $ExportPath -Parent - if ($exportDirectory -and -not (Test-Path -Path $exportDirectory)) { - New-Item -Path $exportDirectory -ItemType Directory -Force | Out-Null - } - - # Create export object with test results - $exportData = @{ - TestDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss" - TestResult = if ($connectivityResult) { "Passed" } else { "Failed" } - NetworkConfiguration = $NetworkConfiguration - } - - # Add endpoint test results if available - if ($script:passedEndpointList -and $script:passedEndpointList.Count -gt 0) { - $exportData["PassedEndpoints"] = $script:passedEndpointList - } - if ($script:failedEndpointList -and $script:failedEndpointList.Count -gt 0) { - $exportData["FailedEndpoints"] = $script:failedEndpointList - } - - # Export to JSON format - $exportData | ConvertTo-Json -Depth 10 | Out-File -FilePath $ExportPath -Encoding UTF8 - Write-Host "`nTest results exported to: $ExportPath" -ForegroundColor Green - - # Verify the export file was created successfully - if (-not (Test-Path -Path $ExportPath)) { - Write-Warning "Export file was not created successfully at: $ExportPath" - } - } - catch { - Write-Warning "Failed to export test results: $($_.Exception.Message)" - } -} - -# Exit with appropriate exit code based on connectivity test results -# Exit code 0 = All mandatory endpoints accessible -# Exit code 1 = One or more mandatory endpoints failed -if ($connectivityResult) { - exit 0 -} else { - exit 1 -} +<# +.SYNOPSIS + Tests connectivity to Microsoft Intune and Microsoft 365 endpoints required for Intune management. + +.DESCRIPTION + This script tests connectivity to all mandatory Intune and Microsoft 365 Common endpoints + required for Intune device management functionality. It queries Microsoft's Office 365 IP + Address and URL web service to obtain the latest endpoint URLs for Service Area "MEM" + (Microsoft Endpoint Manager) and "M365 Common", then tests connectivity to those endpoints + from the client device. The script handles proxy configurations and provides detailed + output about which endpoints are accessible. + + An endpoint counts as reachable when it answers over HTTP(S) with any status code. A 403 or 404 + from the service still proves the network path works. A timeout, DNS failure or refused + connection counts as a failure. Endpoints that only publish a UDP port (NTP, for example) + cannot be tested over HTTP and are reported as skipped. So are wildcard-only entries such as + "*.microsoftonline.com": the bare domain has no address record, so there is no host to test, and + the old script reported every one of them as a failure. + + Endpoint IDs that are not in the built-in category tables are listed as NOT TESTED, not skipped + silently. Add -IncludeUnlistedEndpoints to test them too, using the service's own "required" + flag to decide whether each is mandatory. + + If either endpoint list cannot be retrieved, the test fails. It never reports success after + skipping the Intune endpoints. + +.PARAMETER IncludeUnlistedEndpoints + Also test endpoint sets whose ID is not in the built-in category tables (new Microsoft + endpoints), treating the service's "required" flag as the mandatory flag. + +.PARAMETER ExportPath + Optional path to export test results to a JSON file. + If specified, test results including network configuration and endpoint status will be saved. + +.EXAMPLE + .\Test-IntuneConnectivity.ps1 + +.EXAMPLE + .\Test-IntuneConnectivity.ps1 -ExportPath "C:\Temp\ConnectivityTest.json" + +.NOTES + Prerequisites: + - PowerShell 3.0 or later + - PS script execution policy: Bypass (or appropriate policy to allow script execution) + - Does not require elevation (runs with current user permissions) + - Internet connectivity to reach Microsoft endpoints + + The script: + - Queries Microsoft's endpoint web service for the latest endpoint URLs + - Tests connectivity to mandatory Intune and M365 Common endpoints + - Handles proxy configurations automatically + - Displays network configuration information for troubleshooting + - Exports results as JSON when -ExportPath is given + + Exit Codes: + - 0: All mandatory endpoints are reachable + - 1: A mandatory endpoint is unreachable, or an endpoint list could not be retrieved +#> + +[CmdletBinding()] +param( + [Parameter(Mandatory=$false)] + [string]$ExportPath, + + [Parameter(Mandatory=$false)] + [switch]$IncludeUnlistedEndpoints +) + +# Function to invoke endpoint API with retry logic +# Handles transient failures (429, 503, etc.) with exponential backoff. +# Defined at script scope so every endpoint function can reach it. +function Invoke-EndpointApiWithRetry { + [CmdletBinding()] + param( + [Parameter(Mandatory=$true)] + [string]$Uri, + + [Parameter(Mandatory=$false)] + [int]$MaxRetries = 3, + + [Parameter(Mandatory=$false)] + [int]$InitialDelaySeconds = 2 + ) + + $retryCount = 0 + $delaySeconds = $InitialDelaySeconds + + while ($retryCount -le $MaxRetries) { + try { + $response = Invoke-RestMethod -Uri $Uri -ErrorAction Stop + return $response + } + catch { + $statusCode = $null + if ($_.Exception.Response) { $statusCode = [int]$_.Exception.Response.StatusCode } + + # Retryable: 429 Too Many Requests, 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout + if ($statusCode -in @(429, 502, 503, 504) -and $retryCount -lt $MaxRetries) { + $retryCount++ + Write-Verbose "Endpoint API call failed with status $statusCode. Retrying in $delaySeconds seconds (attempt $retryCount of $MaxRetries)..." + Start-Sleep -Seconds $delaySeconds + $delaySeconds = $delaySeconds * 2 + } + else { + throw + } + } + } +} + +Function ConvertFrom-NetshProxyOutput { + <# + .SYNOPSIS + Turns the text of "netsh winhttp show proxy" into a proxy URL or "NoProxy". + + .DESCRIPTION + Takes the value after "Proxy Server(s) :" as is. TrimStart() with a string trims a set of + characters, not a prefix, and turned "server1.contoso.com:8080" into "1.contoso.com:8080". + A per-protocol list such as "http=a:80;https=b:443" yields the https entry. + + .OUTPUTS + String: a proxy URL with an http:// prefix, or "NoProxy" + #> + param( + [Parameter(Mandatory=$false)] + [string[]]$Lines + ) + + $text = @($Lines) -join "`n" + if ($text -match 'Direct access') { return "NoProxy" } + + if ($text -match '(?m)Proxy Server\(s\)\s*:\s*(\S.*?)\s*$') { + $value = $Matches[1] + + if ($value -match '=') { + $entries = @{} + foreach ($part in ($value -split ';')) { + if ($part -match '^\s*(\w+)=(.+?)\s*$') { $entries[$Matches[1].ToLower()] = $Matches[2] } + } + $value = if ($entries.ContainsKey('https')) { $entries['https'] } elseif ($entries.ContainsKey('http')) { $entries['http'] } else { $null } + if (-not $value) { return "NoProxy" } + } + elseif ($value -match ';') { + $value = ($value -split ';')[0].Trim() + } + + if ($value -notmatch '^https?://') { $value = "http://" + $value } + return $value + } + + return "NoProxy" +} + +Function Get-ProxySettings { + <# + .SYNOPSIS + Retrieves the current Windows HTTP proxy configuration. + + .DESCRIPTION + This function checks the system's winHTTP proxy settings using netsh command. + It determines if the system is using a proxy server or has direct internet access. + Returns the proxy server address or "NoProxy" if direct access is configured. + + .OUTPUTS + String: Proxy server address (with http:// prefix) or "NoProxy" + #> + + Write-Host "Checking winHTTP proxy settings..." -ForegroundColor Yellow + + $ProxyServer = ConvertFrom-NetshProxyOutput -Lines (netsh winhttp show proxy) + + if ($ProxyServer -eq "NoProxy") { + Write-Host "Access Type : DIRECT" + } + else { + Write-Host "Access Type : PROXY" + Write-Host "Proxy Server List :" $ProxyServer + } + + return $ProxyServer +} + +Function Get-EndpointList { + <# + .SYNOPSIS + Retrieves the endpoint list for one service area from Microsoft's endpoint web service. + + .DESCRIPTION + Queries https://endpoints.office.com for one service area ("Common" or "MEM"), attaches a + category and a mandatory flag from the built-in table, strips wildcard prefixes and removes + duplicate URLs. Wildcard-only entries are kept apart in wildcardUrls because there is no host + to test. IDs that are not in the table are kept: their category is "Other (id N)", known is + $false, and the service's own "required" flag is the mandatory flag. + A failure to retrieve the list throws. It is never turned into an empty list. + + .OUTPUTS + Array: objects with id, category, urls, wildcardUrls, known, tcpPorts, udpPorts and mandatory + #> + [CmdletBinding()] + param( + [Parameter(Mandatory=$true)] + [ValidateSet('Common', 'MEM')] + [string]$ServiceArea, + + [Parameter(Mandatory=$true)] + [object[]]$CategoryTable + ) + + $uri = "https://endpoints.office.com/endpoints/WorldWide?ServiceAreas=$ServiceArea&clientrequestid=" + ([GUID]::NewGuid()).Guid + $endpointList = @(Invoke-EndpointApiWithRetry -Uri $uri | Where-Object { $_.ServiceArea -eq $ServiceArea -and $_.urls }) + + $result = @() + foreach ($endpoint in $endpointList) { + $known = $CategoryTable | Where-Object { $_.id -eq $endpoint.id } | Select-Object -First 1 + + # A URL with a * in it is a wildcard. "*.example.com" is also published as plain "example.com" when + # that host exists, so keep only the concrete names to test and list the wildcards separately. + $urls = @($endpoint.urls | Where-Object { $_ -notlike '*`**' } | Sort-Object -Unique) + $wildcardUrls = @($endpoint.urls | Where-Object { $_ -like '*`**' } | Sort-Object -Unique) + + $result += [PSCustomObject]@{ + id = $endpoint.id + category = if ($known) { $known.category } else { "Other (id $($endpoint.id))" } + urls = $urls + wildcardUrls = $wildcardUrls + known = [bool]$known + tcpPorts = "$($endpoint.tcpPorts)" + udpPorts = "$($endpoint.udpPorts)" + mandatory = if ($known) { [bool]$known.mandatory } else { [bool]$endpoint.required } + } + } + return $result +} + +Function Get-M365CommonEndpointList { + <# + .SYNOPSIS + Retrieves the list of Microsoft 365 Common endpoints required for Intune connectivity. + + .OUTPUTS + Array: Processed endpoint list with category and URL information + #> + + # mandatory = $true indicates these endpoints are required for Intune to function + [PsObject[]]$categories = @() + $categories += [PsObject]@{id = 56; category = 'M365 Common'; mandatory = $true } + $categories += [PsObject]@{id = 59; category = 'M365 Common'; mandatory = $true } + $categories += [PsObject]@{id = 78; category = 'M365 Common'; mandatory = $true } + $categories += [PsObject]@{id = 83; category = 'M365 Common'; mandatory = $true } + $categories += [PsObject]@{id = 84; category = 'M365 Common'; mandatory = $true } + $categories += [PsObject]@{id = 125; category = 'M365 Common'; mandatory = $true } + $categories += [PsObject]@{id = 156; category = 'M365 Common'; mandatory = $true } + + return Get-EndpointList -ServiceArea 'Common' -CategoryTable $categories +} + +Function Get-IntuneEndpointList { + <# + .SYNOPSIS + Retrieves the list of Microsoft Endpoint Manager (Intune) endpoints required for connectivity. + + .OUTPUTS + Array: Processed endpoint list with category and URL information + #> + + # mandatory = $true: Endpoints required for basic Intune functionality + # mandatory = $false: Optional endpoints (e.g., platform-specific or feature-specific) + [PsObject[]]$categories = @() + $categories += [PsObject]@{id = 163; category = 'Global'; mandatory = $true } + $categories += [PsObject]@{id = 164; category = 'Delivery Optimization'; mandatory = $true } + $categories += [PsObject]@{id = 165; category = 'NTP Sync'; mandatory = $true } + $categories += [PsObject]@{id = 169; category = 'Windows Notifications & Store'; mandatory = $true } + $categories += [PsObject]@{id = 170; category = 'Scripts & Win32 Apps'; mandatory = $true } + $categories += [PsObject]@{id = 171; category = 'Push Notifications'; mandatory = $true } + $categories += [PsObject]@{id = 172; category = 'Delivery Optimization'; mandatory = $true } + $categories += [PsObject]@{id = 173; category = 'Autopilot Self-deploy'; mandatory = $true } + $categories += [PsObject]@{id = 178; category = 'Apple Device Management'; mandatory = $false } + $categories += [PsObject]@{id = 179; category = 'Android (AOSP) Device Management'; mandatory = $false } + $categories += [PsObject]@{id = 181; category = 'Remote Help'; mandatory = $false } + $categories += [PsObject]@{id = 182; category = 'Collect Diagnostics'; mandatory = $true } + $categories += [PsObject]@{id = 186; category = 'Microsoft Azure attestation - Windows 11 only'; mandatory = $true } + $categories += [PsObject]@{id = 187; category = 'Android Remote Help'; mandatory = $false } + $categories += [PsObject]@{id = 188; category = 'Remote Help GCC Dependency'; mandatory = $false } + $categories += [PsObject]@{id = 189; category = 'Feature Flighting'; mandatory = $false } + + return Get-EndpointList -ServiceArea 'MEM' -CategoryTable $categories +} + +Function Get-EndpointRegionNote { + <# + .SYNOPSIS + Returns the tenant-region note for Intune's regional scale-unit hosts, or an empty string. + #> + param( + [Parameter(Mandatory=$true)] + [string]$Url + ) + + if ($Url -match '^approdimedata') { return 'Asia & Pacific' } + if ($Url -match '^euprodimedata') { return 'Europe' } + if ($Url -match '^naprodimedata') { return 'North America' } + if ($Url -match '^intunemaape(\d+)\.') { + $n = [int]$Matches[1] + if ($n -ge 1 -and $n -le 6) { return 'North America' } + if ($n -ge 7 -and $n -le 12) { return 'Europe' } + if ($n -in @(13, 17, 18, 19)) { return 'Asia & Pacific' } + } + return '' +} + +Function Test-EndpointReachable { + <# + .SYNOPSIS + Tests one endpoint over HTTP(S). Any HTTP answer, including 3xx/4xx/5xx, means reachable. + + .OUTPUTS + Object: Reachable (bool), StatusCode (int or $null), Error (string or $null) + #> + param( + [Parameter(Mandatory=$true)] + [string]$Url, + + [Parameter(Mandatory=$true)] + [ValidateSet('https', 'http')] + [string]$Scheme, + + [Parameter(Mandatory=$false)] + [string]$ProxyServer = "NoProxy" + ) + + $uri = "${Scheme}://$Url" + $parameters = @{ Uri = $uri; UseBasicParsing = $true; TimeoutSec = 10; ErrorAction = 'Stop' } + if ($ProxyServer -ne "NoProxy") { $parameters['Proxy'] = $ProxyServer } + + try { + $response = Invoke-WebRequest @parameters + return [PSCustomObject]@{ Reachable = $true; StatusCode = [int]$response.StatusCode; Error = $null } + } + catch { + # An HTTP error status still means the host answered + if ($_.Exception.Response) { + return [PSCustomObject]@{ Reachable = $true; StatusCode = [int]$_.Exception.Response.StatusCode; Error = $null } + } + return [PSCustomObject]@{ Reachable = $false; StatusCode = $null; Error = $_.Exception.Message } + } +} + +Function Test-EndpointSet { + <# + .SYNOPSIS + Tests every URL of every mandatory endpoint in a list and records the results. + + .OUTPUTS + Boolean: $true if every tested mandatory URL was reachable + #> + param( + [Parameter(Mandatory=$true)] + [object[]]$EndpointList, + + [Parameter(Mandatory=$false)] + [string]$ProxyServer = "NoProxy" + ) + + $allPassed = $true + + foreach ($endpoint in $EndpointList) { + # Only test mandatory endpoints (skip optional ones) + if ($endpoint.mandatory -ne $true) { continue } + + Write-Host "Checking Category: ..." $endpoint.category -ForegroundColor Yellow + + foreach ($wildcard in @($endpoint.wildcardUrls)) { + if (-not $wildcard) { continue } + if (-not $script:skippedEndpointList.ContainsKey($endpoint.category)) { $script:skippedEndpointList[$endpoint.category] = @() } + $script:skippedEndpointList[$endpoint.category] += $wildcard + } + + # Pick the schemes from the published TCP ports. UDP only (NTP) or no TCP 80/443 cannot be tested over HTTP. + # No ports published at all: try https, then http. + $ports = @("$($endpoint.tcpPorts)" -split ',' | ForEach-Object { $_.Trim() }) + # Hosts that publish "80,443" often answer on only one of them (CRL and OCSP hosts answer on 80 only), + # so try https first and then http. A host is reachable if either answers. + $schemes = @() + if ($ports -contains '443') { $schemes += 'https' } + if ($ports -contains '80') { $schemes += 'http' } + if ($schemes.Count -eq 0 -and -not $endpoint.tcpPorts -and -not $endpoint.udpPorts) { $schemes = @('https', 'http') } + + foreach ($url in $endpoint.urls) { + if ($schemes.Count -eq 0) { + if (-not $script:skippedEndpointList.ContainsKey($endpoint.category)) { $script:skippedEndpointList[$endpoint.category] = @() } + $script:skippedEndpointList[$endpoint.category] += $url + Write-Host "Connection to " $url ".............. Skipped (no TCP 80/443 published, cannot be tested over HTTP)." -ForegroundColor Yellow + continue + } + + $test = $null + foreach ($scheme in $schemes) { + $test = Test-EndpointReachable -Url $url -Scheme $scheme -ProxyServer $ProxyServer + if ($test.Reachable) { break } + } + $region = Get-EndpointRegionNote -Url $url + $regionText = if ($region) { " (needed for $region tenants only)" } else { "" } + + if ($test.Reachable) { + if (-not $script:passedEndpointList.ContainsKey($endpoint.category)) { $script:passedEndpointList[$endpoint.category] = @() } + $script:passedEndpointList[$endpoint.category] += $url + Write-Host "Connection to " $url ".............. Succeeded$regionText." -ForegroundColor Green + } + else { + $allPassed = $false + if (-not $script:failedEndpointList.ContainsKey($endpoint.category)) { $script:failedEndpointList[$endpoint.category] = @() } + $script:failedEndpointList[$endpoint.category] += $url + Write-Host "Connection to " $url ".............. Failed$regionText." -ForegroundColor Red + } + } + } + + return $allPassed +} + +Function Test-DeviceIntuneConnectivity { + <# + .SYNOPSIS + Tests connectivity to all required Intune and Microsoft 365 endpoints. + + .DESCRIPTION + Retrieves the M365 Common and Intune (MEM) endpoint lists and tests the mandatory ones. + If either list cannot be retrieved or comes back empty, the test fails. The retrieval + errors are shown, not hidden. + + .OUTPUTS + Boolean: $true if all mandatory endpoints are accessible, $false otherwise + #> + param( + [Parameter(Mandatory=$false)] + [switch]$IncludeUnlisted + ) + + $script:failedEndpointList = @{} # failed endpoints by category (script-level for export) + $script:passedEndpointList = @{} # passed endpoints by category (script-level for export) + $script:skippedEndpointList = @{} # endpoints that could not be tested over HTTP, and wildcard entries + $script:notTestedEndpointIds = @() # endpoint IDs outside the built-in tables, when -IncludeUnlistedEndpoints is off + + $ProxyServer = Get-ProxySettings + + $endpointListM365Common = @() + $endpointListIntune = @() + $retrievalFailed = $false + + try { $endpointListM365Common = @(Get-M365CommonEndpointList) } + catch { + Write-Error "Get-M365CommonEndpointList: Failed to retrieve M365 Common endpoints - $($_.Exception.Message)" + $retrievalFailed = $true + } + try { $endpointListIntune = @(Get-IntuneEndpointList) } + catch { + Write-Error "Get-IntuneEndpointList: Failed to retrieve Intune endpoints - $($_.Exception.Message)" + $retrievalFailed = $true + } + + if ($endpointListM365Common.Count -eq 0 -and -not $retrievalFailed) { + Write-Error "The M365 Common endpoint list is empty." + $retrievalFailed = $true + } + if ($endpointListIntune.Count -eq 0 -and -not $retrievalFailed) { + Write-Error "The Intune (MEM) endpoint list is empty." + $retrievalFailed = $true + } + if ($retrievalFailed) { + Write-Host "Connectivity test could not run: an endpoint list was not retrieved. Intune endpoints must not be skipped." -ForegroundColor Red + return $false + } + + $unknown = @(($endpointListM365Common + $endpointListIntune) | Where-Object { -not $_.known }) + if ($unknown.Count -gt 0) { + $ids = ($unknown | ForEach-Object { $_.id }) -join ', ' + if ($IncludeUnlisted) { + Write-Host "Note: $($unknown.Count) endpoint set(s) are not in the built-in category tables and are tested using the service's own 'required' flag: $ids" -ForegroundColor Yellow + } + else { + Write-Host "Note: $($unknown.Count) endpoint set(s) are not in the built-in category tables and were NOT TESTED: $ids. Use -IncludeUnlistedEndpoints to test them." -ForegroundColor Yellow + $script:notTestedEndpointIds = @($unknown | ForEach-Object { $_.id }) + $endpointListM365Common = @($endpointListM365Common | Where-Object { $_.known }) + $endpointListIntune = @($endpointListIntune | Where-Object { $_.known }) + } + } + + Write-Host "Starting Connectivity Check..." -ForegroundColor Yellow + + $m365Passed = Test-EndpointSet -EndpointList $endpointListM365Common -ProxyServer $ProxyServer + $intunePassed = Test-EndpointSet -EndpointList $endpointListIntune -ProxyServer $ProxyServer + $TestFailed = -not ($m365Passed -and $intunePassed) + + if ($TestFailed) { + Write-Host "Test failed. Please check the following URLs:" -ForegroundColor Red + foreach ($failedEndpoint in $script:failedEndpointList.Keys) { + Write-Host $failedEndpoint -ForegroundColor Red + foreach ($failedUrl in $script:failedEndpointList[$failedEndpoint]) { + Write-Host $failedUrl -ForegroundColor Red + } + } + Write-Host "Test-DeviceIntuneConnectivity completed with failures." -ForegroundColor Yellow -BackgroundColor Black + return $false + } + + Write-Host "Test-DeviceIntuneConnectivity completed successfully." -ForegroundColor Green -BackgroundColor Black + return $true +} + +### Main Execution Section ### + +# Execute the connectivity test function +# This tests all mandatory Intune and M365 Common endpoints +$connectivityResult = Test-DeviceIntuneConnectivity -IncludeUnlisted:$IncludeUnlistedEndpoints + +# Display network configuration information +# This helps troubleshoot connectivity issues by showing the device's network setup +$NetworkConfiguration = @() + +# Get network configuration for all network interfaces +Get-NetIPConfiguration | ForEach-Object { + # Handle null values gracefully to prevent errors + $NetworkConfiguration += New-Object PSObject -Property @{ + InterfaceAlias = $_.InterfaceAlias # Network adapter name + ProfileName = if($null -ne $_.NetProfile.Name){$_.NetProfile.Name}else{""} # Network profile (Domain/Private/Public) + IPv4Address = if($null -ne $_.IPv4Address){$_.IPv4Address}else{""} # IPv4 address + IPv6Address = if($null -ne $_.IPv6Address){$_.IPv6Address}else{""} # IPv6 address + IPv4DefaultGateway = if($null -ne $_.IPv4DefaultGateway){$_.IPv4DefaultGateway.NextHop}else{""} # IPv4 gateway + IPv6DefaultGateway = if($null -ne $_.IPv6DefaultGateway){$_.IPv6DefaultGateway.NextHop}else{""} # IPv6 gateway + DNSServer = if($null -ne $_.DNSServer){$_.DNSServer.ServerAddresses}else{""} # DNS server addresses + } +} + +# Display the network configuration in a formatted table +$NetworkConfiguration | Format-Table -AutoSize + +# Export results to file if path is specified +if ($ExportPath) { + try { + # Create directory if it doesn't exist + $exportDirectory = Split-Path -Path $ExportPath -Parent + if ($exportDirectory -and -not (Test-Path -Path $exportDirectory)) { + New-Item -Path $exportDirectory -ItemType Directory -Force | Out-Null + } + + # Create export object with test results + $exportData = @{ + TestDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss" + TestResult = if ($connectivityResult) { "Passed" } else { "Failed" } + NetworkConfiguration = $NetworkConfiguration + } + + # Add endpoint test results if available + if ($script:passedEndpointList -and $script:passedEndpointList.Count -gt 0) { + $exportData["PassedEndpoints"] = $script:passedEndpointList + } + if ($script:failedEndpointList -and $script:failedEndpointList.Count -gt 0) { + $exportData["FailedEndpoints"] = $script:failedEndpointList + } + if ($script:notTestedEndpointIds -and $script:notTestedEndpointIds.Count -gt 0) { + $exportData["NotTestedEndpointIds"] = $script:notTestedEndpointIds + } + if ($script:skippedEndpointList -and $script:skippedEndpointList.Count -gt 0) { + $exportData["SkippedEndpoints"] = $script:skippedEndpointList + } + + # Export to JSON format + $exportData | ConvertTo-Json -Depth 10 | Out-File -FilePath $ExportPath -Encoding UTF8 + Write-Host "`nTest results exported to: $ExportPath" -ForegroundColor Green + + # Verify the export file was created successfully + if (-not (Test-Path -Path $ExportPath)) { + Write-Warning "Export file was not created successfully at: $ExportPath" + } + } + catch { + Write-Warning "Failed to export test results: $($_.Exception.Message)" + } +} + +# Exit with appropriate exit code based on connectivity test results +# Exit code 0 = All mandatory endpoints accessible +# Exit code 1 = One or more mandatory endpoints failed, or an endpoint list could not be retrieved +if ($connectivityResult) { + exit 0 +} else { + exit 1 +} diff --git a/Troubleshooting/Test-IntuneEnrollment.ps1 b/Troubleshooting/Test-IntuneEnrollment.ps1 index 56d2f01..75c8765 100644 --- a/Troubleshooting/Test-IntuneEnrollment.ps1 +++ b/Troubleshooting/Test-IntuneEnrollment.ps1 @@ -4,253 +4,171 @@ .DESCRIPTION This script checks the local device to verify if it is properly enrolled in Microsoft Intune. - It checks enrollment status, MDM authority, enrollment date, and management state. + It reads the MDM enrollment records under HKLM:\SOFTWARE\Microsoft\Enrollments, picks the ones + whose ProviderID is "MS DM Server" (the Intune MDM provider), and checks that the enrollment + state says enrolled. It also reports the enrolling user, the Intune device ID and first sync + time when they exist, and the state of the Intune Management Extension service. The script can be run locally on the device to verify enrollment status. + The Enrollments key always holds subkeys that are not enrollments (Context, Status, + ValidNodePaths and others). The script skips them instead of failing on them. + .EXAMPLE .\Test-IntuneEnrollment.ps1 .NOTES Exit Codes: - - 0: Device is properly enrolled in Intune - - 1: Device is not enrolled or enrollment issues detected + - 0: Device is enrolled in Intune (an enrollment with ProviderID "MS DM Server" and EnrollmentState 1) + - 1: Device is not enrolled, enrollment state is not "enrolled", or an error occurred #> [CmdletBinding()] param() +# Read one registry value without throwing when the value does not exist. +# Get-ItemPropertyValue throws a terminating error for a missing value and -ErrorAction +# SilentlyContinue does not stop that, so read the whole key and look for the property instead. +function Get-RegistryValueOrNull { + [CmdletBinding()] + param( + [Parameter(Mandatory=$true)] + [string]$Path, + + [Parameter(Mandatory=$true)] + [string]$Name + ) + + $properties = Get-ItemProperty -Path $Path -ErrorAction SilentlyContinue + if ($null -eq $properties) { return $null } + $property = $properties.PSObject.Properties[$Name] + if ($null -eq $property) { return $null } + return $property.Value +} + +# Collect the MDM enrollment records that belong to Intune. +# Intune's MDM provider ID is "MS DM Server". Subkeys without a ProviderID are not enrollments. +function Get-IntuneEnrollmentRecord { + [CmdletBinding()] + param( + [Parameter(Mandatory=$false)] + [string]$EnrollmentsPath = "HKLM:\SOFTWARE\Microsoft\Enrollments" + ) + + $records = @() + if (-not (Test-Path -Path $EnrollmentsPath)) { return $records } + + foreach ($key in @(Get-ChildItem -Path $EnrollmentsPath -ErrorAction SilentlyContinue)) { + $providerId = Get-RegistryValueOrNull -Path $key.PSPath -Name "ProviderID" + if (-not $providerId) { continue } + + $dmClientPath = Join-Path $key.PSPath "DMClient\MS DM Server" + $records += [PSCustomObject]@{ + KeyName = $key.PSChildName + ProviderID = $providerId + IsIntune = ($providerId -eq 'MS DM Server') + EnrollmentState = Get-RegistryValueOrNull -Path $key.PSPath -Name "EnrollmentState" + EnrollmentType = Get-RegistryValueOrNull -Path $key.PSPath -Name "EnrollmentType" + UPN = Get-RegistryValueOrNull -Path $key.PSPath -Name "UPN" + FirstSyncTime = Get-RegistryValueOrNull -Path $key.PSPath -Name "FirstSyncTime" + IntuneDeviceId = Get-RegistryValueOrNull -Path $dmClientPath -Name "EntDMID" + } + } + return $records +} + # Main script execution wrapped in try-catch for error handling try { Write-Host "Testing Intune enrollment status..." -ForegroundColor Yellow Write-Host "====================================" -ForegroundColor Yellow - - # Initialize enrollment status variables - # These will track various enrollment indicators - $isEnrolled = $false + $enrollmentIssues = @() - $enrollmentInfo = @{} - - # Check 1: Verify MDM enrollment in registry - # The registry path contains MDM enrollment information - Write-Host "`n[1/5] Checking MDM enrollment registry..." -ForegroundColor Cyan + + # Check 1: MDM enrollment records + Write-Host "`n[1/3] Checking MDM enrollment registry..." -ForegroundColor Cyan $mdmEnrollmentPath = "HKLM:\SOFTWARE\Microsoft\Enrollments" - - if (Test-Path -Path $mdmEnrollmentPath) { - # Get all enrollment subkeys - # Each enrollment has a GUID subkey - $enrollmentKeys = Get-ChildItem -Path $mdmEnrollmentPath -ErrorAction SilentlyContinue - - if ($enrollmentKeys) { - Write-Host " Found $($enrollmentKeys.Count) enrollment key(s)." -ForegroundColor Green - - # Check each enrollment for Intune/MDM authority - foreach ($key in $enrollmentKeys) { - $providerId = Get-ItemPropertyValue -Path $key.PSPath -Name "ProviderID" -ErrorAction SilentlyContinue - $enrollmentType = Get-ItemPropertyValue -Path $key.PSPath -Name "EnrollmentType" -ErrorAction SilentlyContinue - - # Check if this is an Intune/MDM enrollment - # Intune uses specific provider IDs and enrollment types - if ($providerId -and $enrollmentType) { - Write-Host " Provider ID: $providerId" -ForegroundColor White - Write-Host " Enrollment Type: $enrollmentType" -ForegroundColor White - - # Check for Intune-specific indicators - if ($providerId -like "*Intune*" -or $providerId -like "*Microsoft*") { - $isEnrolled = $true - $enrollmentInfo["ProviderID"] = $providerId - $enrollmentInfo["EnrollmentType"] = $enrollmentType - } - } - } - } - else { - $enrollmentIssues += "No enrollment keys found in registry" - Write-Host " No enrollment keys found." -ForegroundColor Red - } - } - else { + if (-not (Test-Path -Path $mdmEnrollmentPath)) { $enrollmentIssues += "MDM enrollment registry path not found" Write-Host " MDM enrollment registry path not found." -ForegroundColor Red } - - # Check 2: Verify MDM authority - # Check the MDM authority setting which indicates the management service - Write-Host "`n[2/5] Checking MDM authority..." -ForegroundColor Cyan - - try { - # Get MDM authority from registry - # This indicates which MDM service is managing the device - $mdmAuthority = Get-ItemPropertyValue -Path "HKLM:\SOFTWARE\Microsoft\Enrollments" -Name "MDMAuthority" -ErrorAction SilentlyContinue - - if ($mdmAuthority) { - Write-Host " MDM Authority: $mdmAuthority" -ForegroundColor Green - $enrollmentInfo["MDMAuthority"] = $mdmAuthority - - # Check if MDM authority is Intune - if ($mdmAuthority -eq "Intune" -or $mdmAuthority -like "*Intune*") { - $isEnrolled = $true - } - else { - $enrollmentIssues += "MDM Authority is not Intune: $mdmAuthority" - Write-Host " Warning: MDM Authority is not Intune." -ForegroundColor Yellow - } - } - else { - # Try alternative method to find MDM authority - $enrollmentKeys = Get-ChildItem -Path "HKLM:\SOFTWARE\Microsoft\Enrollments" -ErrorAction SilentlyContinue - foreach ($key in $enrollmentKeys) { - $providerPath = Join-Path $key.PSPath "DMClient\Provider" - if (Test-Path -Path $providerPath) { - $providerId = Get-ItemPropertyValue -Path $providerPath -Name "ProviderID" -ErrorAction SilentlyContinue - if ($providerId) { - Write-Host " Provider ID: $providerId" -ForegroundColor Green - $enrollmentInfo["ProviderID"] = $providerId - if ($providerId -like "*Intune*" -or $providerId -like "*Microsoft*") { - $isEnrolled = $true - } - } - } - } - - if (-not $mdmAuthority) { - $enrollmentIssues += "MDM Authority not found" - Write-Host " MDM Authority not found." -ForegroundColor Red - } - } + + $records = @(Get-IntuneEnrollmentRecord -EnrollmentsPath $mdmEnrollmentPath) + $intuneRecords = @($records | Where-Object { $_.IsIntune }) + + if ($records.Count -gt 0) { + Write-Host " Found $($records.Count) enrollment record(s), $($intuneRecords.Count) with the Intune provider (MS DM Server)." -ForegroundColor Green } - catch { - $enrollmentIssues += "Error checking MDM authority: $($_.Exception.Message)" - Write-Host " Error checking MDM authority." -ForegroundColor Red + else { + $enrollmentIssues += "No enrollment records with a ProviderID found in registry" + Write-Host " No enrollment records found." -ForegroundColor Red } - - # Check 3: Verify enrollment date - # Check when the device was enrolled - Write-Host "`n[3/5] Checking enrollment date..." -ForegroundColor Cyan - try { - $enrollmentDate = Get-ItemPropertyValue -Path "HKLM:\SOFTWARE\Microsoft\Enrollments\*\FirstSyncTime" -ErrorAction SilentlyContinue - - if ($enrollmentDate) { - Write-Host " Enrollment Date: $enrollmentDate" -ForegroundColor Green - $enrollmentInfo["EnrollmentDate"] = $enrollmentDate - } - else { - # Try alternative method - $enrollmentKeys = Get-ChildItem -Path "HKLM:\SOFTWARE\Microsoft\Enrollments" -ErrorAction SilentlyContinue - foreach ($key in $enrollmentKeys) { - $firstSync = Get-ItemPropertyValue -Path $key.PSPath -Name "FirstSyncTime" -ErrorAction SilentlyContinue - if ($firstSync) { - Write-Host " Enrollment Date: $firstSync" -ForegroundColor Green - $enrollmentInfo["EnrollmentDate"] = $firstSync - break - } - } - - if (-not $enrollmentInfo["EnrollmentDate"]) { - $enrollmentIssues += "Enrollment date not found" - Write-Host " Enrollment date not found." -ForegroundColor Yellow - } - } + foreach ($record in $records) { + Write-Host " $($record.KeyName): ProviderID=$($record.ProviderID) EnrollmentState=$($record.EnrollmentState) EnrollmentType=$($record.EnrollmentType)" -ForegroundColor White } - catch { - $enrollmentIssues += "Error checking enrollment date: $($_.Exception.Message)" - Write-Host " Error checking enrollment date." -ForegroundColor Red + + # Check 2: enrollment state. EnrollmentState 1 means enrolled. + Write-Host "`n[2/3] Checking enrollment state..." -ForegroundColor Cyan + $enrolledRecord = $intuneRecords | Where-Object { "$($_.EnrollmentState)" -eq '1' } | Select-Object -First 1 + $isEnrolled = ($null -ne $enrolledRecord) + + if ($isEnrolled) { + Write-Host " Enrolled. User: $($enrolledRecord.UPN)" -ForegroundColor Green + if ($enrolledRecord.IntuneDeviceId) { Write-Host " Intune device ID: $($enrolledRecord.IntuneDeviceId)" -ForegroundColor White } + if ($enrolledRecord.FirstSyncTime) { Write-Host " First sync: $($enrolledRecord.FirstSyncTime)" -ForegroundColor White } } - - # Check 4: Verify device is managed - # Check if the device is actually being managed by MDM - Write-Host "`n[4/5] Checking device management status..." -ForegroundColor Cyan - try { - # Check for MDM enrollment status - $isManaged = $false - - # Check registry for management status - $enrollmentKeys = Get-ChildItem -Path "HKLM:\SOFTWARE\Microsoft\Enrollments" -ErrorAction SilentlyContinue - foreach ($key in $enrollmentKeys) { - $isEnrolledValue = Get-ItemPropertyValue -Path $key.PSPath -Name "IsEnrolled" -ErrorAction SilentlyContinue - if ($isEnrolledValue -eq 1 -or $isEnrolledValue -eq $true) { - $isManaged = $true - Write-Host " Device is enrolled: $isEnrolledValue" -ForegroundColor Green - $enrollmentInfo["IsEnrolled"] = $isEnrolledValue - break - } - } - - if (-not $isManaged) { - $enrollmentIssues += "Device management status not confirmed" - Write-Host " Device management status not confirmed." -ForegroundColor Yellow - } + elseif ($intuneRecords.Count -gt 0) { + $states = ($intuneRecords | ForEach-Object { $_.EnrollmentState }) -join ', ' + $enrollmentIssues += "Intune enrollment record found but EnrollmentState is not 1 (found: $states)" + Write-Host " Intune enrollment record found, but its state is not 'enrolled' (EnrollmentState: $states)." -ForegroundColor Red } - catch { - $enrollmentIssues += "Error checking management status: $($_.Exception.Message)" - Write-Host " Error checking management status." -ForegroundColor Red + else { + $enrollmentIssues += "No enrollment with ProviderID 'MS DM Server' found" + Write-Host " No Intune (MS DM Server) enrollment found." -ForegroundColor Red } - - # Check 5: Verify Intune Management Extension (if applicable) - # Check if Intune Management Extension is installed and running - Write-Host "`n[5/5] Checking Intune Management Extension..." -ForegroundColor Cyan - try { - $imeService = Get-Service -Name "IntuneManagementExtension" -ErrorAction SilentlyContinue - - if ($imeService) { - Write-Host " Intune Management Extension service found." -ForegroundColor Green - Write-Host " Service Status: $($imeService.Status)" -ForegroundColor $(if ($imeService.Status -eq 'Running') { 'Green' } else { 'Yellow' }) - $enrollmentInfo["IMEServiceStatus"] = $imeService.Status - - if ($imeService.Status -ne 'Running') { - $enrollmentIssues += "Intune Management Extension service is not running" - } - } - else { - Write-Host " Intune Management Extension service not found (may not be required)." -ForegroundColor Yellow + + # Check 3: Intune Management Extension service + Write-Host "`n[3/3] Checking Intune Management Extension..." -ForegroundColor Cyan + $imeService = Get-Service -Name "IntuneManagementExtension" -ErrorAction SilentlyContinue + if ($imeService) { + Write-Host " Intune Management Extension service found." -ForegroundColor Green + Write-Host " Service Status: $($imeService.Status)" -ForegroundColor $(if ($imeService.Status -eq 'Running') { 'Green' } else { 'Yellow' }) + if ($imeService.Status -ne 'Running') { + $enrollmentIssues += "Intune Management Extension service is not running" } } - catch { - Write-Host " Intune Management Extension service check skipped (may not be installed)." -ForegroundColor Yellow + else { + Write-Host " Intune Management Extension service not found (installed only once a Win32 app or script is assigned)." -ForegroundColor Yellow } - + # Summary Write-Host "`n====================================" -ForegroundColor Yellow Write-Host "Enrollment Test Summary" -ForegroundColor Cyan Write-Host "====================================" -ForegroundColor Yellow - + if ($isEnrolled) { - Write-Host "`nResult: Device appears to be enrolled in Intune." -ForegroundColor Green - - # Display enrollment information - Write-Host "`nEnrollment Information:" -ForegroundColor Cyan - foreach ($key in $enrollmentInfo.Keys) { - Write-Host " $key : $($enrollmentInfo[$key])" -ForegroundColor White - } - - # Display any issues found + Write-Host "`nResult: Device is enrolled in Intune." -ForegroundColor Green if ($enrollmentIssues.Count -gt 0) { Write-Host "`nIssues Found:" -ForegroundColor Yellow foreach ($issue in $enrollmentIssues) { Write-Host " - $issue" -ForegroundColor Yellow } } - exit 0 } else { Write-Host "`nResult: Device does not appear to be enrolled in Intune." -ForegroundColor Red - - # Display issues found if ($enrollmentIssues.Count -gt 0) { Write-Host "`nIssues Found:" -ForegroundColor Red foreach ($issue in $enrollmentIssues) { Write-Host " - $issue" -ForegroundColor Red } } - exit 1 } } # Error handling block - catches exceptions during enrollment checks catch { - # Capture and display the error message with script name for context $errMsg = $_.Exception.Message Write-Error "Test-IntuneEnrollment: Failed to test Intune enrollment - $errMsg" if ($PSBoundParameters.ContainsKey('Verbose')) { @@ -261,4 +179,3 @@ catch } exit 1 } -