Repository navigation
Audit fixes (2026-11-18) - #1
Merged
Merged
Conversation
Set-OfficeUpdateChannel.ps1 assigned the whole officeVersions list's cdnBaseUrl (15 identical strings) to CDNBaseUrl, so the comparison never matched, the registry write took an array and the script always exited 1 (audit C1). It now reduces the channel to exactly one URL and refuses to write if there is not exactly one. The updater path pointed at Office16, which does not exist on Click-to-Run; it now uses Common Files\Microsoft Shared\ClickToRun\OfficeC2RClient.exe and a missing updater or a non-zero updater exit is a failure. -WhatIf skips the post-check in the Set-Office and Repair-MultipleIntuneMDMCert scripts, so a dry run exits 0 instead of reporting that the change it did not make failed (M1). Both Office scripts relaunch in 64-bit PowerShell when started in a 32-bit host and forward -WhatIf/-Verbose (M2). Detect-OfficeUpdateChannel now separates compliant, not applicable (no Click-to-Run), cannot determine (no registry or network) and non-compliant, and no longer calls a build that is only behind "not using Semi-Annual" (M4). Only the last case exits 1, which is the Intune Remediations contract, so devices without Office or network stop looping through remediation. Adds Pester 5 tests with an in-memory registry and certificate store. Every state-changing cmdlet has an unfiltered default mock that throws. The Set-Office tests fail against the pre-fix script (10 of 14) and pass against this one. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DTrMSXN5wTpRJ4nUgD1bRi
Both scripts wrapped every registry write in -ErrorAction SilentlyContinue inside try/catch, so the catch could never fire. They always logged "completed successfully", exited 0, and then deleted their own log (which the final Write-Log recreated with one line), so a failed security change left no trace (audit H4). Each write now uses -ErrorAction Stop, is read back and compared, and any failure makes the script exit 1. The log is always kept; -KeepLogs stays as a no-op so existing callers do not break. Values are written as DWORD explicitly. Enable-SmartCardLogonEnforcement requires a smart card for every interactive logon, local administrator included, with no check that a card could ever be used (H3). It now runs a preflight before any write and refuses with exit 1 unless SCPolicySvc exists and a working smart card reader is present. -Force skips the check for a supervised run. The header documents the lockout risk and the recovery path. The check cannot see cards or certificates; that limit is stated. The 64-bit relaunch passed no parameters, so -WhatIf was silently dropped and the 64-bit child made real changes (M3). It now forwards every switch that was passed. -WhatIf also creates no log file. A missing SCPolicySvc key is no longer created as a bare key with only a Start value (L2): Enable fails on it, Disable skips it. Write-Log is renamed Write-ScriptLog so it does not shadow a built-in cmdlet name. Pester tests use an in-memory registry and service table with unfiltered throwing default mocks. Run against the pre-fix Enable script, 11 of the 21 tests fail. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DTrMSXN5wTpRJ4nUgD1bRi
Test-IntuneEnrollment.ps1 (audit H1) used Get-ItemPropertyValue with -ErrorAction SilentlyContinue. A missing value raises a terminating error that SilentlyContinue does not stop, and the Enrollments key always holds subkeys with no ProviderID (Context, Status, ValidNodePaths, GUID keys), so the script crashed with exit 1 on this machine under both PowerShell 5.1 and 7 before it judged anything. It now reads the key with Get-ItemProperty and checks for the property. It matches the Intune provider as ProviderID "MS DM Server" (the old *Intune* / *Microsoft* wildcards matched neither it nor reality) and requires EnrollmentState 1. It no longer reads values that do not exist (MDMAuthority at the root, IsEnrolled). Not run against an enrolled device; there is none here. Start-MDMSync.ps1 (H7) now declares #Requires -PSEdition Desktop, because the WinRT MdmSessionManager type cannot load in PowerShell 7. The state check looked for Error and Failed, which are not members of MdmSessionState, and never read ExtendedError, so a session that completed with an error was reported as success. It now reads ExtendedError, reports Completed-with-error as exit 1, and no longer gives up after six identical states, which ended in exit 1 instead of the documented timeout exit 2. Get-IntuneDeviceLogs.ps1 (M11) always exited 0 and printed "completed successfully" after listing its own failures. It now exits 1 on any failed collection, on a failed reg.exe or wevtutil.exe, or when no log source exists. It asks for real event log names (the bare provider name is not a log), records "Windows Event Logs" only if one was exported, and restricts an output folder it creates to SYSTEM and Administrators because the logs hold device and user identifiers. Adds Pester tests. Test-IntuneEnrollment and Get-IntuneDeviceLogs tests fail against the pre-fix scripts. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DTrMSXN5wTpRJ4nUgD1bRi
Get-IntuneEndpointList called Invoke-EndpointApiWithRetry, which was defined inside Get-M365CommonEndpointList and so out of scope. The error was caught, Write-Error ran under a function-wide $ErrorActionPreference of SilentlyContinue, and the function returned an empty list. With the M365 half working the script printed "completed successfully" and exited 0 without ever testing manage.microsoft.com or any other MEM endpoint (audit H2, reproduced against the old code). The retry function is now at script scope, the two list functions share one Get-EndpointList, endpoint retrieval errors are shown and throw, and the test fails if either list is missing or empty. The function-wide SilentlyContinue is gone. Other M12 defects: the proxy parser used TrimStart() with a string, which trims a character set, so server1.contoso.com:8080 became 1.contoso.com:8080. It now parses the netsh text with a regex and handles per-protocol lists. An endpoint now counts as reachable on any HTTP answer, not only 200, and a host that publishes ports 80 and 443 is tried on https and then http, because CRL and OCSP hosts answer on 80 only. Duplicate test loops are folded into one function. The export gains skipped endpoints, and the README's claim of CSV export is fixed in the README commit. Found while checking against the live service: wildcard-only entries such as *.microsoftonline.com had their "*." stripped, leaving a bare domain with no address record that failed on every machine. They are now listed as skipped. UDP-only entries (NTP) are skipped, not failed over HTTP. Endpoint IDs missing from the built-in tables are reported as NOT TESTED instead of silently dropped; -IncludeUnlistedEndpoints tests them using the service's own "required" flag. Live run from this machine (read-only GETs): 81 reachable, 3 failed (activity.windows.com and adl.windows.com have no address record, windowsphone.com does not complete TLS), 1 skipped (NTP), exit 1. Those three are quirks of Microsoft's published list and are left as reported failures. The file is converted from CRLF to LF, which is why the diff is large. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DTrMSXN5wTpRJ4nUgD1bRi
…scaping Nine of the module's ten exported functions had no caller and each script repeated its own token request, placeholder check and paging loop (audit L1). The module now carries the pieces the reporting scripts need, so they can actually use it: - Get-IntuneCredential resolves AppId, TenantId and the secret from parameters or INTUNE_* variables, rejects placeholders, and returns the secret as a SecureString. Get-GraphAccessToken accepts a SecureString secret (new Secure parameter set) next to the plain string it already took, and Get-IntuneGraphHeaders returns the ready-to-use headers (M7). - ConvertTo-ODataStringLiteral doubles single quotes, which is OData's escape. Remove-ODataInjectionChars and Test-ODataFilterInput deleted quote and semicolon characters, so a name with an apostrophe was altered and never matched. They now double the quote and keep the rest (L1). Combined with [uri]::EscapeDataString on the finished filter, a UPN containing + now matches (L4). - Protect-CsvValue and ConvertTo-SafeCsvRecord prefix a leading = + - @ tab or CR with an apostrophe so device names and UPNs cannot run as spreadsheet formulas (L3). - ConvertTo-Array gets a process block; the header author is no longer "Intune Scripts Collection". - IntuneCommon.psd1 adds the missing manifest (version 1.1.0, explicit export list). Pester tests cover each piece, the 429 Retry-After path and paging across nextLink pages, with Invoke-RestMethod mocked inside the module. A URI with no route throws. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DTrMSXN5wTpRJ4nUgD1bRi
…lling Graph The "No assignments" branch tested $null -eq $assignments.value, but an empty list parses to an empty array, not $null, so the branch was dead and unassigned policies, the usual reason to run this report, vanished from the output (audit H5, same pattern in the compliance half). The list is now counted. A policy whose assignments call fails gets a TargetType "Error" row, the report says it is incomplete and the script exits 1. Policy lists and assignments are paged through Get-GraphApiAllPages (M8). M6: the script no longer runs Install-Module or Import-Module Microsoft.Graph. It never used an SDK cmdlet, so the install was a side effect that could pull the full meta-module (and its 5.1 function- capacity problem) onto an admin's machine for nothing. M7: adds -ClientSecretSecure, takes credentials through Get-IntuneCredential, and the help now says the permissions must be Application permissions with admin consent. CSV output goes through ConvertTo-SafeCsvRecord (L3). Group names are resolved once per group. The report summary counts real assignments, unassigned policies and errors separately. Pester tests run the script end to end against a mocked Graph. They assert the unassigned row, the error row and exit code, paging, exclusion targets, formula neutralising, no Install-Module, SecureString and environment credentials, and no HTTP call with a placeholder credential. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DTrMSXN5wTpRJ4nUgD1bRi
The CompliancePolicies column held every compliance policy in the tenant (/deviceCompliancePolicies),
written identically onto every device, and the header promised non-compliance reasons it never read
(audit H5). Each device now gets its own policy states from managedDevices/{id}/deviceCompliancePolicyStates,
as "Name (state)", plus a NonCompliantPolicies column for nonCompliant, error and conflict states. A
device whose states cannot be read gets a CollectionError value, the report says it is incomplete and
the script exits 1. Per-setting reasons are not retrieved; the header now says so. -SkipPolicyStates
drops the one-request-per-device cost on large tenants.
M8: the device list is read through Get-GraphApiAllPages, including the UPN-filtered query that read
only the first page. L4: the UPN filter goes through ConvertTo-ODataStringLiteral and is URL-encoded, so
a UPN containing + now matches. M6: no Install-Module or Import-Module Microsoft.Graph. M7: adds
-ClientSecretSecure and documents Application permissions. L3: CSV output is formula-safe. The pointless
$expand=detectedApps on the single-device call is gone.
Tests run the script against a mocked Graph and assert per-device columns, the error row and exit code,
paging, the encoded filter, -SkipPolicyStates, formula neutralising and no module install.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DTrMSXN5wTpRJ4nUgD1bRi
The -DeviceName search read only the first page (audit M8), built its filter by deleting apostrophes and semicolons from the name (so O'Brien-PC searched for OBrien-PC) and sent the filter without URL encoding. The search is now paged through Get-GraphApiAllPages, doubles quotes (OData's escape) and URL-encodes the filter. Wildcard characters are removed rather than expanded, because contains() is a literal substring match, so the README's -DeviceName 'LAPTOP-*' example never matched anything useful; the help now says it is a substring match. M6: no Install-Module or Import-Module Microsoft.Graph, since the script never used an SDK cmdlet. M7: adds -ClientSecretSecure and documents Application permissions. L3: CSV output is formula-safe. The three copies of the device-to-row mapping are one function. Tests cover paging, the apostrophe and encoding, the wildcard rule, formula neutralising, 403 handling and no module install. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DTrMSXN5wTpRJ4nUgD1bRi
The "supported" management agent list was MDM, EAS and IntuneClient, so every other Graph managementAgentType value (easMdm, configurationManagerClientMdm for co-managed devices, microsoft365ManagedMdm, msSense and others) got "Unsupported management agent" and lost 10 points (audit M10, checked against the Microsoft Learn managementAgentType enum). The check now accepts the full enum and penalises only "unknown" or a missing value. It also dropped the penalty for an enrollment older than a year, which is not a health problem. A device that has never synced reports lastSyncDateTime as 0001-01-01T00:00:00Z rather than null, so it was scored "Stale" and not "Never Synced". The placeholder is now recognised. The weights stay a rule of thumb but are named in one table and listed in the help. Scoring moves into Get-DeviceHealthAssessment, which takes the clock as a parameter and is tested directly. The script also reads the device list through Get-GraphApiAllPages, no longer runs Install-Module/Import-Module Microsoft.Graph (M6), takes -ClientSecretSecure (M7), checks a single-device fetch for null, and writes formula-safe CSV (L3). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DTrMSXN5wTpRJ4nUgD1bRi
A failed assignments call was replaced by an empty list and logged only at -Verbose, so a 403 or an
exhausted 429 showed as "AssignmentCount = 0" in a report that looked complete (audit H5). The failure
is now recorded as an AssignmentError on that app, the count is left blank, the report says it is
incomplete and the script exits 1. A genuine zero stays 0.
M9: the per-device "Installed" state compared detectedApps display names (software inventory such as
"7-Zip 24.08 (x64)") to the Intune app name with -eq, which almost never matches, so most apps read
"Not Installed". It now reads mobileApps/{id}/deviceStatuses and matches on deviceId, reporting Graph's own
installState and displayVersion, or "NotReported" when Intune holds no row for that device. That is one
paged request per app, stated in the help. A failed single-app fetch used to be caught with Write-Error
and the script still said "completed successfully" and exited 0; it now exits 1.
M8: the app list is read through Get-GraphApiAllPages. M6: no Install-Module/Import-Module
Microsoft.Graph. M7: -ClientSecretSecure and the documented Application permission. L3: formula-safe CSV.
Not run against a tenant: the deviceStatuses shape follows the Graph mobileAppInstallStatus resource and
is exercised only with mocks.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DTrMSXN5wTpRJ4nUgD1bRi
…g them The per-device compliance and configuration state calls passed -ErrorAction SilentlyContinue into a function that throws, and the catch only wrote a -Verbose line, so a 403 or an exhausted 429 left CompliancePolicies and ConfigurationProfiles blank for every device in a report that looked complete (audit H5). A failed call is now counted, recorded on the device as CollectionErrors, the file is still written, and the script exits 1 with a message that the report is incomplete. The state lists are paged through Get-GraphApiAllPages (M8). M6: no Install-Module/Import-Module Microsoft.Graph. M7: -ClientSecretSecure; the header no longer lists DeviceManagementApps.Read.All, which this script never uses, and states that the permissions are Application permissions with admin consent. L3: CSV is formula-safe. The -OutputPath default is documented as a timestamped file. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DTrMSXN5wTpRJ4nUgD1bRi
…rameter Audit H6, all three read-and-run verified: - The README documented -ExportCSVpath, which the script did not have; line 83 hard-coded the TEMP file, so the README example failed with "A parameter cannot be found". The parameter now exists, defaulting to $env:TEMP\Get-IntuneAllAppsAssignmentDetails.csv. - Only allLicensedUsers and allDevices targets were handled; every other target, including exclusionGroupAssignmentTarget, fell into the group branch and was written as a targeted group. Each row now has a TargetType (All Users, All Devices, Group, Excluded group), so an exclusion is never shown as a deployment. - One Invoke-MgGraphRequest with $expand and no @odata.nextLink handling truncated the report on a large tenant. Every page is now read. The script still queries the beta endpoint with the same $expand, as before; whether v1.0 returns the same fields was not tested. The script no longer needs the Microsoft.Graph SDK (M6): it used Connect-MgGraph, Invoke-MgGraphRequest and Get-MgGroup for three calls. They are replaced with the shared REST helpers, which also removes the ConvertTo-SecureString -AsPlainText token conversion that PSScriptAnalyzer flagged as an Error. Group names are cached so each group is resolved once. M7: -ClientSecretSecure and documented Application permissions (DeviceManagementApps.Read.All and Group.Read.All). L3: CSV is formula-safe. The file is converted from CRLF to LF, which is why the diff is large. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DTrMSXN5wTpRJ4nUgD1bRi
Enable-PrintSpoolerService slept 10 seconds between Set-Service and Start-Service for no reason (audit L6); Set-Service has applied the startup type when it returns. The sleep is gone. Disable-PrintSpoolerService used Stop-Service -Force, which also stops every running dependent service. It now warns about running dependents and stops without -Force, so a dependent makes the stop fail with a clear message and exit 1 instead of being taken down silently. If you want the old behaviour back, add -Force; this is a judgment call and is listed for review. The UTF-8 byte order mark on that file is removed so every script is plain ASCII. Tests mock the service cmdlets, assert -WhatIf changes nothing, and check both files are ASCII. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DTrMSXN5wTpRJ4nUgD1bRi
…werShell 5.1 Adds PSScriptAnalyzerSettings.psd1 (errors and warnings fail; Write-Host and the singular-noun style rule are excluded on purpose) and fixes what remained: Get-IntuneGraphHeaders takes -AppRegistration instead of a "Credential" parameter that PSScriptAnalyzer read as a plain-text password; the one intended ConvertTo-SecureString on an already-plain input and the string-only Remove-ODataInjectionChars carry a justified suppression; two inner functions are renamed so they do not claim a state-changing verb. The audit's single PSScriptAnalyzer Error (ConvertTo-SecureString -AsPlainText in the all-apps script) was removed with the SDK in the earlier commit. Four tests are adjusted for Windows PowerShell 5.1 differences found by running the suite there: a Where-Object result needs @() before .Count, [uri]::ToString() decodes more in 5.1, and Exception.HResult has no public setter, so the tests use COMException. The suite passes 195 of 195 in both 5.1 and 7. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DTrMSXN5wTpRJ4nUgD1bRi
CI (.github/workflows/ci.yml): PSScriptAnalyzer with the repository settings, a parse check of every script, and Pester 5.9.1 on both pwsh 7 and Windows PowerShell 5.1. PSScriptAnalyzer is pinned to 1.25.0. The only action, actions/checkout, is pinned to the full commit SHA of v4.2.2 taken from git ls-remote. Not run on GitHub: nothing was pushed. README rewritten to match the code (audit M5, M6, M7, M12, H3, H6, L1, L8): Remediations versus custom compliance and the 64-bit setting, Application permissions and admin consent per script, no automatic Microsoft.Graph install, SecureString and environment-variable credentials, the smart card lockout warning and recovery path, the real -ExportCSVpath and its default, JSON (not CSV) export for the connectivity test, the Windows PowerShell 5.1 requirement for Start-MDMSync, and the Testing section. "Production-ready" is replaced by a statement of what is and is not tested. The Detect-MultipleIntuneMDMCert header no longer calls the script a compliance-policy script. .gitignore allows fixtures under Tests\ although *.json and *.csv stay ignored elsewhere. CHANGELOG.md added. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DTrMSXN5wTpRJ4nUgD1bRi
Review blocker: mobileApps/{id}/deviceStatuses is documented only in the Graph beta endpoint, and the
script called v1.0. In a real tenant the call would fail and every app would show DeviceStatusError.
That one call now uses beta; the rest of the script stays on v1.0. The test routes are pinned to the
full beta URL, so a v1.0 call hits no route and the tests fail (checked: 2 of 9 fail with v1.0).
README and help say the endpoint is beta only. Still mock-proven only; not run against a tenant.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DTrMSXN5wTpRJ4nUgD1bRi
Review finding: scforceoption=1 was written first, so a later failure (for example the service step) exited 1 but left the device requiring a smart card. It is now the last step, is written only if ScRemoveOption and the service step succeeded, and if its own write or read-back fails the previous value (or 0, the Windows default) is put back, with the rollback itself reported if it fails. Tests: service failure and ScRemoveOption failure leave scforceoption unwritten, the write order ends with scforceoption, and a read-back mismatch rolls the value back. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DTrMSXN5wTpRJ4nUgD1bRi
…eal string checks Review finding: four reads still used Get-ItemPropertyValue -ErrorAction SilentlyContinue, which throws for a missing value, so a device missing CDNBaseUrl or VersionToReport crashed to exit 1 instead of being remediated. They now go through Get-RegistryValueOrNull (Get-ItemProperty and a property check). The test mock now behaves like the real cmdlet (Get-ItemPropertyValue throws for a missing value), and a new test runs with an empty registry key. The "-BeOfType [string]" assertions passed for an array because Pester checks each element; they are replaced by an -is [string] check plus a count of 1 (Set-Office and the proxy parser test). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DTrMSXN5wTpRJ4nUgD1bRi
Get-IntuneGraphHeaders is new on this branch, so changing its parameter name is not a breaking change; the changelog and analyzer-settings comment said otherwise. The changelog now discloses that ConvertTo-Array processes each pipeline item. README states that a detection script which cannot read its state (Detect-OfficeUpdateChannel) exits 0 with "Cannot determine", the one deliberate exception to "a script that could not finish does not exit 0". The changelog also records the beta deviceStatuses call and the smart card write order. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DTrMSXN5wTpRJ4nUgD1bRi
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes from a code audit on 2026-11-18.
Changes
Notes
Tests: 201 Pester tests pass on PowerShell 7 and 5.1. Graph calls are mocked; nothing here has run against a live tenant.
🤖 Generated with Claude Code
https://claude.ai/code/session_01DTrMSXN5wTpRJ4nUgD1bRi