From 7747fb81403b1b114d0e2939a89cbbe07ec82f87 Mon Sep 17 00:00:00 2001 From: Jeffrey Stuhr <110697945+fadwen@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:02:41 -0800 Subject: [PATCH 1/2] feat(harness): preview a run with -WhatIf instead of half-running it With $WhatIfPreference set in the caller's session, the runtime harness neither previewed a run nor made it. None of its commands declared SupportsShouldProcess, so the preference went straight to the cmdlets they call: Copy-Item skipped the copy of the script, the host was started on the file that was not there, and its complaint came back as the result of the script, with exit code -196608. On the scheduled-task path the task was registered and started, since those cmdlets have no -WhatIf, and never removed, since Unregister-ScheduledTask has one. A run is a change the caller can ask to preview. The five Invoke-Intune*Test commands now declare SupportsShouldProcess and ask once, after their arguments are checked and before anything runs. Under -WhatIf, or a preference, they say which script or command line they would run, in which context and architecture, and return nothing. Export-IntuneAgentDiagnostic and Export-IntuneFindingSarif ask before they write their file. Get-IntuneScriptHealth still reads the tenant and returns its reports, and asks for the two things it changes: the report export job in the tenant and the Markdown file. The other half is that nothing inside consults the preference. The run folder, the copy of the script, the work folder of Test-IntuneDeployedScript and the removal of the scheduled task pass -WhatIf:$false, and the detections inside a Win32 app flow pass -Confirm:$false, so that one run asks once. Tests/Unit/Module.WhatIf.Tests.ps1 checks the preview on the disk, with scripts that leave a marker file when they run. Refs #88 --- CHANGELOG.md | 13 + CLAUDE.md | 16 ++ Private/Get-IslExportReport.ps1 | 2 +- Private/Invoke-IslProcess.ps1 | 5 +- Private/Invoke-IslScriptRun.ps1 | 9 +- Public/Export-IntuneAgentDiagnostic.ps1 | 5 +- Public/Export-IntuneFindingSarif.ps1 | 5 +- Public/Get-IntuneScriptHealth.ps1 | 17 +- Public/Invoke-IntuneDetectionTest.ps1 | 8 +- Public/Invoke-IntunePlatformScriptTest.ps1 | 8 +- Public/Invoke-IntuneRemediationTest.ps1 | 13 +- Public/Invoke-IntuneRequirementTest.ps1 | 8 +- Public/Invoke-IntuneWin32AppTest.ps1 | 18 +- Public/Test-IntuneDeployedScript.ps1 | 8 +- README.md | 4 + Tests/Unit/Module.WhatIf.Tests.ps1 | 172 ++++++++++++ .../Unit/Private/Invoke-IslProcess.Tests.ps1 | 19 ++ .../Public/Get-IntuneScriptHealth.Tests.ps1 | 14 + .../Test-IntuneDeployedScript.Tests.ps1 | 16 ++ .../Export-IntuneAgentDiagnostic.md | 48 +++- .../Export-IntuneFindingSarif.md | 50 +++- .../IntuneScriptLab/Get-IntuneScriptHealth.md | 48 +++- .../Invoke-IntuneDetectionTest.md | 48 +++- .../Invoke-IntunePlatformScriptTest.md | 48 +++- .../Invoke-IntuneRemediationTest.md | 50 +++- .../Invoke-IntuneRequirementTest.md | 48 +++- .../Invoke-IntuneWin32AppTest.md | 48 +++- en-US/IntuneScriptLab-Help.xml | 256 ++++++++++++++++++ 28 files changed, 964 insertions(+), 40 deletions(-) create mode 100644 Tests/Unit/Module.WhatIf.Tests.ps1 diff --git a/CHANGELOG.md b/CHANGELOG.md index 765a244..33b2038 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,13 @@ entries are carried over from the manifest's release notes. ### Added +- `-WhatIf` and `-Confirm` on the commands that start a script or write a report. The five + `Invoke-Intune*Test` commands say which script or command line they would run, in which context + and architecture, run nothing and return nothing. `Export-IntuneAgentDiagnostic` and + `Export-IntuneFindingSarif` say which file they would write and write nothing. + `Get-IntuneScriptHealth` still reads the tenant and returns its reports under `-WhatIf`, but + creates no report export job, so the device columns of the apps stay empty, and does not write + the file of `-MarkdownPath`. - A Gallery downloads badge in the README that sums the per-version download counts, because the Gallery's own total is broken (PowerShell/PowerShellGallery#347 and #350: 0 for this module, stuck or wrong for others). `.github/workflows/gallery-downloads.yml` reads every version from the v2 @@ -95,6 +102,12 @@ entries are carried over from the manifest's release notes. - A test of `Get-IslAgentLogEvent` read the event table before anything had built it, so it failed whenever the shuffled order of the CI run put it first in its file. It builds the table first. +- With `$WhatIfPreference` set in the caller's session, the runtime harness did neither a preview + nor a run: it skipped copying the script, started the host on the file that was not there, and + returned the host's complaint as the result of the script, with exit code -196608. A run through + a scheduled task, as SYSTEM or as another account, left its `IntuneScriptLab-*` task registered. + The harness now previews, as it does for `-WhatIf`, and the commands that only read, such as + `Test-IntuneDeployedScript`, work the same with the preference as without it. - On Windows PowerShell 5.1, a run that timed out could end with an error instead of a result whose run state is `TimedOut`, when the caller's `$ErrorActionPreference` was `Stop`, as it is in a CI step. The cleanup ends the processes of the run with `taskkill.exe`, which reports a diff --git a/CLAUDE.md b/CLAUDE.md index b71da1e..b461563 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -178,6 +178,22 @@ script, checks the PSScriptAnalyzer rules module is present and that every comma topic serve their help, before anything is uploaded. `Examples/` and `PSScriptAnalyzer/` ship; `Validation/`, `Tests/`, `docs/` and `Build/` do not. +### A command that runs a script or writes a report asks `ShouldProcess`; nothing else does + +`-WhatIf` sets `$WhatIfPreference` for everything a command calls, and a caller's own preference +reaches the module the same way. The cmdlets inside the harness used to obey it: `Copy-Item` +skipped the copy of the script, the host was started on a file that was not there, and its +complaint came back as the script's result (#88). So the rule has two halves. The five +`Invoke-Intune*Test` commands, the two `Export-` commands and `Get-IntuneScriptHealth` declare +`SupportsShouldProcess` and ask once, before anything runs or is written, and return nothing when +the answer is no. Every internal operation - the run folder, the copy, a work folder, the removal +of a scheduled task - passes `-WhatIf:$false`, and a call from one gated command to another passes +`-Confirm:$false`, so that one run asks once. `Tests/Unit/Module.WhatIf.Tests.ps1` checks the +preview on the disk, with scripts that leave a marker file when they run. + +Of the scheduled-task cmdlets only `Unregister-ScheduledTask` has `-WhatIf`. Under a preference +the task was registered and started, and then left behind. + ### `$WhatIfPreference` is inherited by child scopes Under `Publish-Module.ps1 -WhatIf`, the preference reaches the staging cmdlets and `Build-Help.ps1`. diff --git a/Private/Get-IslExportReport.ps1 b/Private/Get-IslExportReport.ps1 index 50b97bb..cf4c57e 100644 --- a/Private/Get-IslExportReport.ps1 +++ b/Private/Get-IslExportReport.ps1 @@ -79,6 +79,6 @@ function Get-IslExportReport { @($csv | ConvertFrom-Csv) } finally { - Remove-Item -LiteralPath $zip -Force -ErrorAction SilentlyContinue + Remove-Item -LiteralPath $zip -Force -ErrorAction SilentlyContinue -WhatIf:$false } } diff --git a/Private/Invoke-IslProcess.ps1 b/Private/Invoke-IslProcess.ps1 index de39f2c..d836315 100644 --- a/Private/Invoke-IslProcess.ps1 +++ b/Private/Invoke-IslProcess.ps1 @@ -258,7 +258,10 @@ } } finally { - Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue + # Of the task cmdlets used here only this one has -WhatIf. Under a preference the + # task would be registered and started and then left behind + $unregisterSplat = @{ TaskName = $taskName; Confirm = $false; WhatIf = $false } + Unregister-ScheduledTask @unregisterSplat -ErrorAction SilentlyContinue } $stopwatch.Stop() $stdout = if (Test-Path -LiteralPath $outFile) { diff --git a/Private/Invoke-IslScriptRun.ps1 b/Private/Invoke-IslScriptRun.ps1 index b6aaf77..35da16b 100644 --- a/Private/Invoke-IslScriptRun.ps1 +++ b/Private/Invoke-IslScriptRun.ps1 @@ -62,9 +62,12 @@ function Invoke-IslScriptRun { else { Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath "IntuneScriptLab\$runId" } - $null = New-Item -ItemType Directory -Path $cache -Force + # The run folder and the copy are this function's own bookkeeping. The command that asked for + # the run has had its -WhatIf answered before it called; with a preference still in effect + # here, the copy would be skipped and the host started on a file that is not there + $null = New-Item -ItemType Directory -Path $cache -Force -WhatIf:$false $scriptCopy = Join-Path -Path $cache -ChildPath "$Phase.ps1" - Copy-Item -LiteralPath $source -Destination $scriptCopy + Copy-Item -LiteralPath $source -Destination $scriptCopy -WhatIf:$false try { $processSplat = @{ @@ -83,7 +86,7 @@ function Invoke-IslScriptRun { $run = Invoke-IslProcess @processSplat } finally { - Remove-Item -LiteralPath $cache -Recurse -Force -ErrorAction SilentlyContinue + Remove-Item -LiteralPath $cache -Recurse -Force -ErrorAction SilentlyContinue -WhatIf:$false } [pscustomobject]@{ diff --git a/Public/Export-IntuneAgentDiagnostic.ps1 b/Public/Export-IntuneAgentDiagnostic.ps1 index 9d946ac..ba452d3 100644 --- a/Public/Export-IntuneAgentDiagnostic.ps1 +++ b/Public/Export-IntuneAgentDiagnostic.ps1 @@ -4,7 +4,7 @@ function Export-IntuneAgentDiagnostic { .SYNOPSIS Packs the agent's logs, its registry state and the parsed timelines into one zip for a ticket. #> - [CmdletBinding()] + [CmdletBinding(SupportsShouldProcess)] [OutputType('IntuneScriptLab.Diagnostic')] param( [Parameter(Mandatory, Position = 0)] @@ -32,6 +32,9 @@ function Export-IntuneAgentDiagnostic { } $PSCmdlet.ThrowTerminatingError((New-IslErrorRecord @recordSplat)) } + if (-not $PSCmdlet.ShouldProcess($zip, 'Write the diagnostic package')) { + return + } if (-not $LogPath) { $programData = if ($env:ProgramData) { $env:ProgramData } else { 'C:\ProgramData' } $LogPath = Join-Path -Path $programData -ChildPath 'Microsoft\IntuneManagementExtension\Logs' diff --git a/Public/Export-IntuneFindingSarif.ps1 b/Public/Export-IntuneFindingSarif.ps1 index d5b149c..9482b90 100644 --- a/Public/Export-IntuneFindingSarif.ps1 +++ b/Public/Export-IntuneFindingSarif.ps1 @@ -4,7 +4,7 @@ function Export-IntuneFindingSarif { .SYNOPSIS Writes IntuneScriptLab findings as a SARIF 2.1.0 log for code scanning. #> - [CmdletBinding()] + [CmdletBinding(SupportsShouldProcess)] [OutputType([System.IO.FileInfo])] param( [Parameter(Mandatory, ValueFromPipeline)] @@ -168,6 +168,9 @@ function Export-IntuneFindingSarif { # Resolved against the PowerShell location: .NET's current directory is not $PWD $outFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path) + if (-not $PSCmdlet.ShouldProcess($outFile, "Write the SARIF log of $($all.Count) result(s)")) { + return + } $folder = Split-Path -Path $outFile -Parent if ($folder) { $null = New-Item -ItemType Directory -Path $folder -Force } $json = $log | ConvertTo-Json -Depth 12 diff --git a/Public/Get-IntuneScriptHealth.ps1 b/Public/Get-IntuneScriptHealth.ps1 index 940c3c3..c8ee140 100644 --- a/Public/Get-IntuneScriptHealth.ps1 +++ b/Public/Get-IntuneScriptHealth.ps1 @@ -4,7 +4,7 @@ function Get-IntuneScriptHealth { .SYNOPSIS One line per deployed script policy: findings, drift, assignment and what the devices report. #> - [CmdletBinding()] + [CmdletBinding(SupportsShouldProcess)] [OutputType('IntuneScriptLab.HealthReport')] param( [ValidateSet('Remediation', 'PlatformScript', 'Win32App')] @@ -82,8 +82,12 @@ function Get-IntuneScriptHealth { } } + # The install counts come from an export job, and creating one is a write to the tenant: + # -WhatIf leaves it out, and the apps' device columns stay empty $appInstall = @{} - if (-not $SkipRunState -and 'Win32App' -in $Kind) { + $wantsExport = -not $SkipRunState -and 'Win32App' -in $Kind + $exportAction = 'Create a report export job for the app install counts' + if ($wantsExport -and $PSCmdlet.ShouldProcess('Microsoft Graph', $exportAction)) { try { foreach ($row in @(Get-IslExportReport -ReportName 'AppInstallStatusAggregate')) { $appInstall["$(Get-IslPropertyValue -InputObject $row -Name 'ApplicationId')"] = $row @@ -302,7 +306,14 @@ function Get-IntuneScriptHealth { } } + # The reports are read from the tenant and are returned in any case. The file is the one + # thing this command writes, and -WhatIf leaves it unwritten + $markdownFile = $null if ($MarkdownPath) { + # Resolved against the PowerShell location: .NET's current directory is not $PWD + $markdownFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($MarkdownPath) + } + if ($markdownFile -and $PSCmdlet.ShouldProcess($markdownFile, 'Write the Markdown report')) { $rank = @{ Broken = 0; Attention = 1; Healthy = 2 } $lines = [System.Collections.Generic.List[string]]::new() $lines.Add('# Intune script health') @@ -324,8 +335,6 @@ function Get-IntuneScriptHealth { } $lines.Add('') } - # Resolved against the PowerShell location: .NET's current directory is not $PWD - $markdownFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($MarkdownPath) [System.IO.File]::WriteAllLines($markdownFile, $lines, [System.Text.UTF8Encoding]::new($false)) Write-Verbose "Markdown report written to $MarkdownPath" } diff --git a/Public/Invoke-IntuneDetectionTest.ps1 b/Public/Invoke-IntuneDetectionTest.ps1 index 7809aae..889bd3f 100644 --- a/Public/Invoke-IntuneDetectionTest.ps1 +++ b/Public/Invoke-IntuneDetectionTest.ps1 @@ -4,7 +4,7 @@ function Invoke-IntuneDetectionTest { .SYNOPSIS Runs a Win32 custom detection script like Intune and returns the verdict. #> - [CmdletBinding()] + [CmdletBinding(SupportsShouldProcess)] [OutputType('IntuneScriptLab.DetectionResult')] param( [Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)] @@ -40,6 +40,12 @@ function Invoke-IntuneDetectionTest { # host exists, and x64 elsewhere if (-not $Architecture) { $Architecture = Get-IslHostArchitecture } + # The script is somebody's code and is about to run: -WhatIf names it and runs nothing + $action = "Run as a Win32 detection script ($Context context, $Architecture)" + if (-not $PSCmdlet.ShouldProcess($Path, $action)) { + return + } + $reasons = [System.Collections.Generic.List[string]]::new() $signatureStatus = '' $run = $null diff --git a/Public/Invoke-IntunePlatformScriptTest.ps1 b/Public/Invoke-IntunePlatformScriptTest.ps1 index 20f0886..305e1ac 100644 --- a/Public/Invoke-IntunePlatformScriptTest.ps1 +++ b/Public/Invoke-IntunePlatformScriptTest.ps1 @@ -4,7 +4,7 @@ function Invoke-IntunePlatformScriptTest { .SYNOPSIS Runs a platform (device) script the way Intune does and reports its run state. #> - [CmdletBinding()] + [CmdletBinding(SupportsShouldProcess)] [OutputType('IntuneScriptLab.PlatformScriptResult')] param( [Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)] @@ -44,6 +44,12 @@ function Invoke-IntunePlatformScriptTest { } $scriptRunSplat.Credential = $Credential } + # The script is somebody's code and is about to run: -WhatIf names it and runs nothing + $action = "Run as a platform script ($Context context, $Architecture)" + if (-not $PSCmdlet.ShouldProcess($Path, $action)) { + return + } + $run = Invoke-IslScriptRun @scriptRunSplat $runState = if ($run.TimedOut) { 'TimedOut' } elseif ($run.ExitCode -eq 0) { 'Success' } else { 'Failed' } diff --git a/Public/Invoke-IntuneRemediationTest.ps1 b/Public/Invoke-IntuneRemediationTest.ps1 index 4a1db30..9692f1d 100644 --- a/Public/Invoke-IntuneRemediationTest.ps1 +++ b/Public/Invoke-IntuneRemediationTest.ps1 @@ -4,7 +4,7 @@ function Invoke-IntuneRemediationTest { .SYNOPSIS Runs a detection/remediation pair like Intune and reports the portal status. #> - [CmdletBinding()] + [CmdletBinding(SupportsShouldProcess)] [OutputType('IntuneScriptLab.RemediationResult')] param( [Parameter(Mandatory, Position = 0)] @@ -43,6 +43,17 @@ function Invoke-IntuneRemediationTest { } $scriptRunSplat.Credential = $Credential } + # The scripts are somebody's code and are about to run: -WhatIf names them and runs nothing + $action = if ($RemediationPath) { + "Run as a remediation ($Context context, $Architecture): the detection, then $RemediationPath " + + 'when the detection reports an issue, then the detection again' + } else { + "Run as a detection-only remediation ($Context context, $Architecture)" + } + if (-not $PSCmdlet.ShouldProcess($DetectionPath, $action)) { + return + } + $pre = Invoke-IslScriptRun -Path $DetectionPath -Phase 'detect' @scriptRunSplat $remediation = $null $post = $null diff --git a/Public/Invoke-IntuneRequirementTest.ps1 b/Public/Invoke-IntuneRequirementTest.ps1 index c6a7096..7052ae7 100644 --- a/Public/Invoke-IntuneRequirementTest.ps1 +++ b/Public/Invoke-IntuneRequirementTest.ps1 @@ -4,7 +4,7 @@ function Invoke-IntuneRequirementTest { .SYNOPSIS Runs a Win32 requirement script like Intune and applies the rule to its output. #> - [CmdletBinding()] + [CmdletBinding(SupportsShouldProcess)] [OutputType('IntuneScriptLab.RequirementResult')] param( [Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)] @@ -59,6 +59,12 @@ function Invoke-IntuneRequirementTest { } $scriptRunSplat.Credential = $Credential } + # The script is somebody's code and is about to run: -WhatIf names it and runs nothing + $action = "Run as a Win32 requirement script ($Context context, $Architecture)" + if (-not $PSCmdlet.ShouldProcess($Path, $action)) { + return + } + $run = Invoke-IslScriptRun @scriptRunSplat $compareSplat = @{ StdOut = $run.StdOut diff --git a/Public/Invoke-IntuneWin32AppTest.ps1 b/Public/Invoke-IntuneWin32AppTest.ps1 index 2aee77b..a80ea03 100644 --- a/Public/Invoke-IntuneWin32AppTest.ps1 +++ b/Public/Invoke-IntuneWin32AppTest.ps1 @@ -4,7 +4,7 @@ function Invoke-IntuneWin32AppTest { .SYNOPSIS Runs a Win32 app's detect, install or uninstall, detect flow the way the Intune agent does. #> - [CmdletBinding()] + [CmdletBinding(SupportsShouldProcess)] [OutputType('IntuneScriptLab.Win32AppResult')] param( [string]$DetectionPath, @@ -105,6 +105,15 @@ function Invoke-IntuneWin32AppTest { } $detectionSplat.Credential = $Credential } + # The command line and the detection script are somebody's code and are about to run: -WhatIf + # names them and runs nothing. The detections below are part of this one run, so they do not + # ask again + $action = "Run the Win32 app flow for intent $Intent ($Context context, $Architecture): $command" + if (-not $PSCmdlet.ShouldProcess($ContentPath, $action)) { + return + } + $detectionSplat['Confirm'] = $false + $runAs = if ($Credential) { $Credential.UserName } elseif ($Context -eq 'System') { 'NT AUTHORITY\SYSTEM' } elseif ($env:USERDOMAIN) { "$env:USERDOMAIN\$env:USERNAME" } @@ -170,8 +179,9 @@ function Invoke-IntuneWin32AppTest { Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath "IntuneScriptLab\$runId" } $copy = Join-Path -Path $cache -ChildPath 'content' - $null = New-Item -ItemType Directory -Path $copy -Force - Copy-Item -Path (Join-Path -Path $source -ChildPath '*') -Destination $copy -Recurse -Force + $null = New-Item -ItemType Directory -Path $copy -Force -WhatIf:$false + $contentItems = Join-Path -Path $source -ChildPath '*' + Copy-Item -Path $contentItems -Destination $copy -Recurse -Force -WhatIf:$false if ($Credential) { Grant-IslFolderAccess -Path $cache -Account $Credential.UserName } try { $cmdFolder = if ([Environment]::Is64BitOperatingSystem) { 'SysWOW64' } else { 'System32' } @@ -189,7 +199,7 @@ function Invoke-IntuneWin32AppTest { $run = Invoke-IslProcess @processSplat } finally { - Remove-Item -LiteralPath $cache -Recurse -Force -ErrorAction SilentlyContinue + Remove-Item -LiteralPath $cache -Recurse -Force -ErrorAction SilentlyContinue -WhatIf:$false } [pscustomobject]@{ PSTypeName = 'IntuneScriptLab.RunResult' diff --git a/Public/Test-IntuneDeployedScript.ps1 b/Public/Test-IntuneDeployedScript.ps1 index 8e52c11..f35281a 100644 --- a/Public/Test-IntuneDeployedScript.ps1 +++ b/Public/Test-IntuneDeployedScript.ps1 @@ -36,7 +36,9 @@ function Test-IntuneDeployedScript { $severityRank = @{ Information = 0; Warning = 1; Error = 2 } $workName = "IntuneScriptLab\preflight-$([guid]::NewGuid().ToString('N'))" $workFolder = Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath $workName - $null = New-Item -ItemType Directory -Path $workFolder -Force + # The work folder is this command's own: it reads the tenant and changes nothing, so a + # caller's -WhatIf preference has no say in it + $null = New-Item -ItemType Directory -Path $workFolder -Force -WhatIf:$false # Mutable state the nested functions share (an assignment inside them would make a local copy) $groupState = @{ Cache = @{}; Blocked = $false } $filterState = @{ Cache = @{}; Blocked = $false } @@ -103,7 +105,7 @@ function Test-IntuneDeployedScript { $policyId = "$(Get-IslPropertyValue -InputObject $Policy -Name 'id')" $safeName = [regex]::Replace($policyName, '[^\w.-]', '_') $folder = Join-Path -Path $workFolder -ChildPath "$PolicyKind\$safeName-$policyId" - $null = New-Item -ItemType Directory -Path $folder -Force + $null = New-Item -ItemType Directory -Path $folder -Force -WhatIf:$false $file = Join-Path -Path $folder -ChildPath "$Role.ps1" # Byte for byte: the encoding rule needs to see the BOM, or its absence, as the tenant stores it [System.IO.File]::WriteAllBytes($file, [System.Convert]::FromBase64String($Content)) @@ -447,7 +449,7 @@ function Test-IntuneDeployedScript { } } finally { - Remove-Item -LiteralPath $workFolder -Recurse -Force -ErrorAction SilentlyContinue + Remove-Item -LiteralPath $workFolder -Recurse -Force -ErrorAction SilentlyContinue -WhatIf:$false } Write-Verbose "Completed $($MyInvocation.MyCommand.Name)" } diff --git a/README.md b/README.md index 45b36f0..e5ce0a8 100644 --- a/README.md +++ b/README.md @@ -192,6 +192,10 @@ Intune does. `-Context User` (the default) runs it as whoever is running the har user-context scripts as the signed-in user, which the harness cannot impersonate, so treat that mode as "the launch shape and the output rules" and `-Context System` as exact. +Each harness command runs somebody's script for real. `-WhatIf` says which script it would run, in +which context and architecture, runs nothing and returns nothing; `-Confirm` asks first. A +`$WhatIfPreference` that a deployment script has set does the same. + ```powershell # Detect -> remediate if the detection exits non-zero -> detect again Invoke-IntuneRemediationTest -DetectionPath .\Detect.ps1 -RemediationPath .\Remediate.ps1 -Architecture x86 diff --git a/Tests/Unit/Module.WhatIf.Tests.ps1 b/Tests/Unit/Module.WhatIf.Tests.ps1 new file mode 100644 index 0000000..9cdaa02 --- /dev/null +++ b/Tests/Unit/Module.WhatIf.Tests.ps1 @@ -0,0 +1,172 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# + What -WhatIf, and a WhatIf preference in the caller's session, do across the module. A command + that starts a script or writes a report previews it: it says what it would do, does none of it + and returns nothing. The scripts here leave a marker file when they run, so that "did not run" + is checked on the disk and not on a mock. + + The preference used to reach the cmdlets inside the harness instead. The copy of the script + was skipped, the host was started on a file that was not there, and its complaint came back as + the result of the script (#88). +#> + +BeforeAll { + $script:ModuleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) + if (-not (Get-Module -Name IntuneScriptLab)) { + Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') + } + . (Join-Path $script:ModuleRoot 'Tests\TestHelpers\TestHelpers.ps1') + + function New-MarkerScript { + <# + .SYNOPSIS + Writes a script that leaves a marker file, writes a line and exits 0. Returns both paths. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', + Justification = 'Writes one script under TestDrive.')] + [CmdletBinding()] + [OutputType([System.Management.Automation.PSCustomObject])] + param( + [Parameter(Mandatory)] + [string]$Name + ) + + $marker = Join-Path $TestDrive "$Name.marker" + $body = "Set-Content -LiteralPath '$marker' -Value 'ran'`r`nWrite-Output 'present'`r`nexit 0" + [pscustomobject]@{ + Script = New-TestScript "$Name\Detect.ps1" $body -Bom + Marker = $marker + } + } +} + +Describe 'What -WhatIf does across the module' -Tag 'Unit', 'Contract' { + + Context 'The fixture' { + It 'leaves its marker when the script does run' { + $probe = New-MarkerScript -Name 'Sanity' + $result = Invoke-IntuneDetectionTest -Path $probe.Script -TimeoutSeconds 60 + + $result.Detected | Should-BeTrue + Test-Path -LiteralPath $probe.Marker | Should-BeTrue + } + } + + Context 'Commands that start a script' { + It 'previews a detection: runs nothing and returns nothing' { + $probe = New-MarkerScript -Name 'Detection' + $result = @(Invoke-IntuneDetectionTest -Path $probe.Script -WhatIf) + + $result.Count | Should-Be 0 + Test-Path -LiteralPath $probe.Marker | Should-BeFalse + } + + It 'previews each script that arrives on the pipeline' { + $first = New-MarkerScript -Name 'PipelineOne' + $second = New-MarkerScript -Name 'PipelineTwo' + $result = @($first.Script, $second.Script | Invoke-IntuneDetectionTest -WhatIf) + + $result.Count | Should-Be 0 + Test-Path -LiteralPath $first.Marker | Should-BeFalse + Test-Path -LiteralPath $second.Marker | Should-BeFalse + } + + It 'previews a platform script' { + $probe = New-MarkerScript -Name 'Platform' + $result = @(Invoke-IntunePlatformScriptTest -Path $probe.Script -WhatIf) + + $result.Count | Should-Be 0 + Test-Path -LiteralPath $probe.Marker | Should-BeFalse + } + + It 'previews a requirement script' { + $probe = New-MarkerScript -Name 'Requirement' + $requirementSplat = @{ Path = $probe.Script; OutputType = 'String'; Value = 'present' } + $result = @(Invoke-IntuneRequirementTest @requirementSplat -WhatIf) + + $result.Count | Should-Be 0 + Test-Path -LiteralPath $probe.Marker | Should-BeFalse + } + + It 'previews a remediation: neither the detection nor the remediation runs' { + $detection = New-MarkerScript -Name 'RemediationDetect' + $remediation = New-MarkerScript -Name 'RemediationFix' + $remediationSplat = @{ DetectionPath = $detection.Script; RemediationPath = $remediation.Script } + $result = @(Invoke-IntuneRemediationTest @remediationSplat -WhatIf) + + $result.Count | Should-Be 0 + Test-Path -LiteralPath $detection.Marker | Should-BeFalse + Test-Path -LiteralPath $remediation.Marker | Should-BeFalse + } + + It 'previews a Win32 app flow: neither the detection nor the install command runs' { + $detection = New-MarkerScript -Name 'AppDetect' + $content = Join-Path $TestDrive 'AppContent' + $null = New-Item -ItemType Directory -Path $content -Force + $installed = Join-Path $TestDrive 'App.installed' + $appSplat = @{ + DetectionPath = $detection.Script + ContentPath = $content + InstallCommand = "cmd.exe /c echo installed > `"$installed`"" + } + $result = @(Invoke-IntuneWin32AppTest @appSplat -WhatIf) + + $result.Count | Should-Be 0 + Test-Path -LiteralPath $detection.Marker | Should-BeFalse + Test-Path -LiteralPath $installed | Should-BeFalse + } + } + + Context 'Commands that write a report' { + It 'previews the diagnostic package: no zip and no result' { + $logs = Join-Path $TestDrive 'NoLogs' + $null = New-Item -ItemType Directory -Path $logs -Force + $zip = Join-Path $TestDrive 'preview.zip' + $result = @(Export-IntuneAgentDiagnostic -Path $zip -LogPath $logs -SkipRegistry -WhatIf) + + $result.Count | Should-Be 0 + Test-Path -LiteralPath $zip | Should-BeFalse + } + + It 'previews the SARIF log: no file and no result' { + $script = New-TestScript 'Sarif\Detect.ps1' "Write-Output 'present'`r`nreturn`r`nexit 0" -Bom + $findings = @(Test-IntuneScript -Path $script -ScriptType Detection) + $sarif = Join-Path $TestDrive 'preview.sarif' + $result = @($findings | Export-IntuneFindingSarif -Path $sarif -Root $TestDrive -WhatIf) + + $findings.Count | Should-BeGreaterThan 0 + $result.Count | Should-Be 0 + Test-Path -LiteralPath $sarif | Should-BeFalse + } + } + + Context 'A WhatIf preference in the caller''s session' { + It 'previews the run as -WhatIf does, and does not start the host on a missing copy' { + $probe = New-MarkerScript -Name 'Preference' + $run = Invoke-CallerScript -Statement @( + "`$WhatIfPreference = `$true" + "`$results = @(Invoke-IntuneDetectionTest -Path '$($probe.Script)')" + "'results: ' + `$results.Count" + ) + + $run.ReachedEnd | Should-BeTrue + @($run.Output | Where-Object { $_ -like 'What if:*' }) | Should-BeCollection -Count 1 + @($run.Output | Where-Object { $_ -like 'results:*' }) | Should-BeCollection @('results: 0') + $run.ErrorId | Should-BeCollection -Count 0 + Test-Path -LiteralPath $probe.Marker | Should-BeFalse + } + + It 'does not reach a command that only reads: the analysis is the same' { + $script = New-TestScript 'Analysis\Detect.ps1' "Write-Output 'present'`r`nreturn`r`nexit 0" -Bom + $expected = @(Test-IntuneScript -Path $script -ScriptType Detection) + $underPreference = @(InModuleScope IntuneScriptLab -Parameters @{ Path = $script } { + $WhatIfPreference = $true + Test-IntuneScript -Path $Path -ScriptType Detection + }) + + $expected.Count | Should-BeGreaterThan 0 + @($underPreference.RuleName | Sort-Object) | Should-BeCollection @($expected.RuleName | Sort-Object) + } + } +} diff --git a/Tests/Unit/Private/Invoke-IslProcess.Tests.ps1 b/Tests/Unit/Private/Invoke-IslProcess.Tests.ps1 index 0fb04ee..ea9fa89 100644 --- a/Tests/Unit/Private/Invoke-IslProcess.Tests.ps1 +++ b/Tests/Unit/Private/Invoke-IslProcess.Tests.ps1 @@ -149,6 +149,25 @@ Describe 'Invoke-IslProcess' -Tag 'Unit', 'Private' { Should-Invoke Unregister-ScheduledTask -ModuleName IntuneScriptLab -Exactly -Times 1 } + It 'removes the task although the caller''s WhatIf preference is on' { + # Of the task cmdlets only Unregister-ScheduledTask has -WhatIf. Under a preference the + # task was registered and started, and then left on the computer + $parameters = @{ + FilePath = 'C:\host\powershell.exe'; Arguments = '-File "x.ps1"' + WorkingDirectory = 'C:\Windows\System32' + WorkFolder = $script:WorkFolder; Context = 'System'; TimeoutSeconds = 30 + } + $result = InModuleScope IntuneScriptLab -Parameters @{ Parameters = $parameters } { + $WhatIfPreference = $true + Invoke-IslProcess @Parameters + } + + $result.ExitCode | Should-Be 5 + Should-Invoke Unregister-ScheduledTask -ModuleName IntuneScriptLab -Exactly -Times 1 -ParameterFilter { + $PesterBoundParameters.ContainsKey('WhatIf') -and -not $WhatIf + } + } + It 'uses the 32-bit cmd.exe when asked, so bare powershell.exe resolves to SysWOW64' { $null = Invoke-Process @{ FilePath = 'powershell.exe'; WorkingDirectory = 'C:\'; WorkFolder = $script:WorkFolder diff --git a/Tests/Unit/Public/Get-IntuneScriptHealth.Tests.ps1 b/Tests/Unit/Public/Get-IntuneScriptHealth.Tests.ps1 index c31a4cb..9e4e1cf 100644 --- a/Tests/Unit/Public/Get-IntuneScriptHealth.Tests.ps1 +++ b/Tests/Unit/Public/Get-IntuneScriptHealth.Tests.ps1 @@ -181,6 +181,20 @@ Describe 'Get-IntuneScriptHealth' -Tag 'Unit', 'Public' { } Context 'Switches' { + It 'returns the reports under -WhatIf, creates no export job and writes no Markdown' { + $file = Join-Path $TestDrive 'whatif.md' + $expected = @(Get-IntuneScriptHealth).Count + $report = @(Get-IntuneScriptHealth -MarkdownPath $file -WhatIf) + + $expected | Should-BeGreaterThan 0 + $report.Count | Should-Be $expected + Test-Path -LiteralPath $file | Should-BeFalse + # Once, for the run without -WhatIf above + Should-Invoke Get-IslExportReport -ModuleName IntuneScriptLab -Times 1 -Exactly + # Without the export the apps have no install counts + ($report | Where-Object PolicyId -eq 'app-a').Succeeded | Should-Be 0 + } + It 'leaves the device columns and the export alone with -SkipRunState' { $report = @(Get-IntuneScriptHealth -SkipRunState) ($report | Where-Object PolicyId -eq 'rem-a').Succeeded | Should-Be 0 diff --git a/Tests/Unit/Public/Test-IntuneDeployedScript.Tests.ps1 b/Tests/Unit/Public/Test-IntuneDeployedScript.Tests.ps1 index e890b00..30d4746 100644 --- a/Tests/Unit/Public/Test-IntuneDeployedScript.Tests.ps1 +++ b/Tests/Unit/Public/Test-IntuneDeployedScript.Tests.ps1 @@ -321,6 +321,22 @@ Describe 'Test-IntuneDeployedScript' -Tag 'Unit', 'Public' { } } + Context 'A WhatIf preference in the caller''s session' { + It 'reads the tenant and analyzes the scripts as it does without one' { + # The command changes nothing, so there is nothing to preview. Its work folder is its + # own: with the preference in effect there, the scripts could not be written to it + $expected = @(Test-IntuneDeployedScript) + $underPreference = @(InModuleScope IntuneScriptLab { + $WhatIfPreference = $true + Test-IntuneDeployedScript + }) + + $expected.Count | Should-BeGreaterThan 0 + $underPreference.Count | Should-Be $expected.Count + @($underPreference.RuleName | Sort-Object) | Should-BeCollection @($expected.RuleName | Sort-Object) + } + } + Context 'Filters' { It 'reads only the kinds asked for' { @(Test-IntuneDeployedScript -Kind PlatformScript).PolicyName | Should-All { $_ -eq 'Set-Wallpaper' } diff --git a/docs/IntuneScriptLab/Export-IntuneAgentDiagnostic.md b/docs/IntuneScriptLab/Export-IntuneAgentDiagnostic.md index a4dad04..6302db5 100644 --- a/docs/IntuneScriptLab/Export-IntuneAgentDiagnostic.md +++ b/docs/IntuneScriptLab/Export-IntuneAgentDiagnostic.md @@ -4,7 +4,7 @@ external help file: IntuneScriptLab-Help.xml HelpUri: https://github.com/fadwen/IntuneScriptLab/blob/main/docs/IntuneScriptLab/Export-IntuneAgentDiagnostic.md Locale: en-US Module Name: IntuneScriptLab -ms.date: 09/28/2026 +ms.date: 11/23/2026 PlatyPS schema version: 2024-05-01 title: Export-IntuneAgentDiagnostic --- @@ -21,7 +21,7 @@ Packs the agent's logs, its registry state and the parsed timelines into one zip ``` Export-IntuneAgentDiagnostic [-Path] [-LogPath ] [-SkipRegistry] [-SkipTimeline] - [-Force] [] + [-Force] [-WhatIf] [-Confirm] ``` ## ALIASES @@ -72,6 +72,28 @@ logs came from. ## PARAMETERS +### -Confirm + +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +DefaultValue: '' +SupportsWildcards: false +Aliases: +- cf +ParameterSets: +- Name: (All) + Position: Named + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + ### -Force Overwrite an existing zip. @@ -180,6 +202,28 @@ AcceptedValues: [] HelpMessage: '' ``` +### -WhatIf + +Says which package would be written, and writes nothing. The command returns nothing. + +```yaml +Type: System.Management.Automation.SwitchParameter +DefaultValue: '' +SupportsWildcards: false +Aliases: +- wi +ParameterSets: +- Name: (All) + Position: Named + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, diff --git a/docs/IntuneScriptLab/Export-IntuneFindingSarif.md b/docs/IntuneScriptLab/Export-IntuneFindingSarif.md index a98ba64..0c5068b 100644 --- a/docs/IntuneScriptLab/Export-IntuneFindingSarif.md +++ b/docs/IntuneScriptLab/Export-IntuneFindingSarif.md @@ -4,7 +4,7 @@ external help file: IntuneScriptLab-Help.xml HelpUri: https://github.com/fadwen/IntuneScriptLab/blob/main/docs/IntuneScriptLab/Export-IntuneFindingSarif.md Locale: en-US Module Name: IntuneScriptLab -ms.date: 09/28/2026 +ms.date: 11/23/2026 PlatyPS schema version: 2024-05-01 title: Export-IntuneFindingSarif --- @@ -20,8 +20,8 @@ Writes IntuneScriptLab findings as a SARIF 2.1.0 log for code scanning. ### __AllParameterSets ``` -Export-IntuneFindingSarif [-Finding] [-Path] [[-Root] ] - [] +Export-IntuneFindingSarif [-Finding] [-Path] [[-Root] ] [-WhatIf] + [-Confirm] ``` ## ALIASES @@ -67,6 +67,28 @@ A valid log with no results, so a clean run still uploads and closes earlier ale ## PARAMETERS +### -Confirm + +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +DefaultValue: '' +SupportsWildcards: false +Aliases: +- cf +ParameterSets: +- Name: (All) + Position: Named + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + ### -Finding The IntuneScriptLab.Finding objects, from Test-IntuneScript or the pipeline. @@ -134,6 +156,28 @@ AcceptedValues: [] HelpMessage: '' ``` +### -WhatIf + +Says which SARIF log would be written and with how many results, and writes nothing. The command returns nothing. + +```yaml +Type: System.Management.Automation.SwitchParameter +DefaultValue: '' +SupportsWildcards: false +Aliases: +- wi +ParameterSets: +- Name: (All) + Position: Named + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, diff --git a/docs/IntuneScriptLab/Get-IntuneScriptHealth.md b/docs/IntuneScriptLab/Get-IntuneScriptHealth.md index bcec463..17fc44f 100644 --- a/docs/IntuneScriptLab/Get-IntuneScriptHealth.md +++ b/docs/IntuneScriptLab/Get-IntuneScriptHealth.md @@ -4,7 +4,7 @@ external help file: IntuneScriptLab-Help.xml HelpUri: https://github.com/fadwen/IntuneScriptLab/blob/main/docs/IntuneScriptLab/Get-IntuneScriptHealth.md Locale: en-US Module Name: IntuneScriptLab -ms.date: 09/28/2026 +ms.date: 11/23/2026 PlatyPS schema version: 2024-05-01 title: Get-IntuneScriptHealth --- @@ -22,7 +22,7 @@ One line per deployed script policy: findings, drift, assignment and what the de ``` Get-IntuneScriptHealth [[-Kind] ] [[-Name] ] [[-Id] ] [[-Path] ] [[-Map] ] [[-Settings] ] [[-MarkdownPath] ] - [-SkipAnalysis] [-SkipRunState] [-SkipGroupLookup] [] + [-SkipAnalysis] [-SkipRunState] [-SkipGroupLookup] [-WhatIf] [-Confirm] ``` ## ALIASES @@ -90,6 +90,28 @@ The findings behind the counts of one policy family. ## PARAMETERS +### -Confirm + +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +DefaultValue: '' +SupportsWildcards: false +Aliases: +- cf +ParameterSets: +- Name: (All) + Position: Named + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + ### -Id Policy ids to report on, in addition to -Name. @@ -305,6 +327,28 @@ AcceptedValues: [] HelpMessage: '' ``` +### -WhatIf + +Reads the tenant and returns the reports, but leaves out the two things the command changes: it creates no report export job, so the device columns of the apps stay empty, and it does not write the file of -MarkdownPath. + +```yaml +Type: System.Management.Automation.SwitchParameter +DefaultValue: '' +SupportsWildcards: false +Aliases: +- wi +ParameterSets: +- Name: (All) + Position: Named + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, diff --git a/docs/IntuneScriptLab/Invoke-IntuneDetectionTest.md b/docs/IntuneScriptLab/Invoke-IntuneDetectionTest.md index e9a83e3..33dbdd9 100644 --- a/docs/IntuneScriptLab/Invoke-IntuneDetectionTest.md +++ b/docs/IntuneScriptLab/Invoke-IntuneDetectionTest.md @@ -4,7 +4,7 @@ external help file: IntuneScriptLab-Help.xml HelpUri: https://github.com/fadwen/IntuneScriptLab/blob/main/docs/IntuneScriptLab/Invoke-IntuneDetectionTest.md Locale: en-US Module Name: IntuneScriptLab -ms.date: 10/06/2026 +ms.date: 11/23/2026 PlatyPS schema version: 2024-05-01 title: Invoke-IntuneDetectionTest --- @@ -21,7 +21,7 @@ Runs a Win32 custom detection script like Intune and returns the verdict. ``` Invoke-IntuneDetectionTest [-Path] [-Architecture ] [-Context ] - [-Credential ] [-TimeoutSeconds ] [-EnforceSignatureCheck] [] + [-Credential ] [-TimeoutSeconds ] [-EnforceSignatureCheck] [-WhatIf] [-Confirm] ``` ## ALIASES @@ -89,6 +89,28 @@ AcceptedValues: [] HelpMessage: '' ``` +### -Confirm + +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +DefaultValue: '' +SupportsWildcards: false +Aliases: +- cf +ParameterSets: +- Name: (All) + Position: Named + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + ### -Context User (default) or System. System runs the script as NT AUTHORITY\SYSTEM in session 0 through a @@ -203,6 +225,28 @@ AcceptedValues: [] HelpMessage: '' ``` +### -WhatIf + +Says which script would be run as a Win32 detection script, in which context and architecture, and runs nothing. The command returns nothing. + +```yaml +Type: System.Management.Automation.SwitchParameter +DefaultValue: '' +SupportsWildcards: false +Aliases: +- wi +ParameterSets: +- Name: (All) + Position: Named + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, diff --git a/docs/IntuneScriptLab/Invoke-IntunePlatformScriptTest.md b/docs/IntuneScriptLab/Invoke-IntunePlatformScriptTest.md index a6f25b9..f2cae0b 100644 --- a/docs/IntuneScriptLab/Invoke-IntunePlatformScriptTest.md +++ b/docs/IntuneScriptLab/Invoke-IntunePlatformScriptTest.md @@ -4,7 +4,7 @@ external help file: IntuneScriptLab-Help.xml HelpUri: https://github.com/fadwen/IntuneScriptLab/blob/main/docs/IntuneScriptLab/Invoke-IntunePlatformScriptTest.md Locale: en-US Module Name: IntuneScriptLab -ms.date: 10/06/2026 +ms.date: 11/23/2026 PlatyPS schema version: 2024-05-01 title: Invoke-IntunePlatformScriptTest --- @@ -21,7 +21,7 @@ Runs a platform (device) script the way Intune does and reports its run state. ``` Invoke-IntunePlatformScriptTest [-Path] [-Architecture ] [-Context ] - [-Credential ] [-TimeoutSeconds ] [] + [-Credential ] [-TimeoutSeconds ] [-WhatIf] [-Confirm] ``` ## ALIASES @@ -84,6 +84,28 @@ AcceptedValues: [] HelpMessage: '' ``` +### -Confirm + +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +DefaultValue: '' +SupportsWildcards: false +Aliases: +- cf +ParameterSets: +- Name: (All) + Position: Named + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + ### -Context User (default) or System. System runs the script as NT AUTHORITY\SYSTEM in session 0 through a @@ -176,6 +198,28 @@ AcceptedValues: [] HelpMessage: '' ``` +### -WhatIf + +Says which script would be run as a platform script, in which context and architecture, and runs nothing. The command returns nothing. + +```yaml +Type: System.Management.Automation.SwitchParameter +DefaultValue: '' +SupportsWildcards: false +Aliases: +- wi +ParameterSets: +- Name: (All) + Position: Named + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, diff --git a/docs/IntuneScriptLab/Invoke-IntuneRemediationTest.md b/docs/IntuneScriptLab/Invoke-IntuneRemediationTest.md index 5724856..750b084 100644 --- a/docs/IntuneScriptLab/Invoke-IntuneRemediationTest.md +++ b/docs/IntuneScriptLab/Invoke-IntuneRemediationTest.md @@ -1,10 +1,10 @@ ---- +--- document type: cmdlet external help file: IntuneScriptLab-Help.xml HelpUri: https://github.com/fadwen/IntuneScriptLab/blob/main/docs/IntuneScriptLab/Invoke-IntuneRemediationTest.md Locale: en-US Module Name: IntuneScriptLab -ms.date: 10/05/2026 +ms.date: 11/23/2026 PlatyPS schema version: 2024-05-01 title: Invoke-IntuneRemediationTest --- @@ -22,7 +22,7 @@ Runs a detection/remediation pair like Intune and reports the portal status. ``` Invoke-IntuneRemediationTest [-DetectionPath] [[-RemediationPath] ] [-Architecture ] [-Context ] [-Credential ] [-TimeoutSeconds ] - [] + [-WhatIf] [-Confirm] ``` ## ALIASES @@ -108,6 +108,28 @@ AcceptedValues: [] HelpMessage: '' ``` +### -Confirm + +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +DefaultValue: '' +SupportsWildcards: false +Aliases: +- cf +ParameterSets: +- Name: (All) + Position: Named + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + ### -Context User (default) or System. System runs the scripts as NT AUTHORITY\SYSTEM in session 0 through a @@ -220,6 +242,28 @@ AcceptedValues: [] HelpMessage: '' ``` +### -WhatIf + +Says which detection script would be run, and which remediation script after it, and runs neither. The command returns nothing. + +```yaml +Type: System.Management.Automation.SwitchParameter +DefaultValue: '' +SupportsWildcards: false +Aliases: +- wi +ParameterSets: +- Name: (All) + Position: Named + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, diff --git a/docs/IntuneScriptLab/Invoke-IntuneRequirementTest.md b/docs/IntuneScriptLab/Invoke-IntuneRequirementTest.md index c82d05a..4bfe8e3 100644 --- a/docs/IntuneScriptLab/Invoke-IntuneRequirementTest.md +++ b/docs/IntuneScriptLab/Invoke-IntuneRequirementTest.md @@ -4,7 +4,7 @@ external help file: IntuneScriptLab-Help.xml HelpUri: https://github.com/fadwen/IntuneScriptLab/blob/main/docs/IntuneScriptLab/Invoke-IntuneRequirementTest.md Locale: en-US Module Name: IntuneScriptLab -ms.date: 10/06/2026 +ms.date: 11/23/2026 PlatyPS schema version: 2024-05-01 title: Invoke-IntuneRequirementTest --- @@ -22,7 +22,7 @@ Runs a Win32 requirement script like Intune and applies the rule to its output. ``` Invoke-IntuneRequirementTest [-Path] -OutputType -Value [-Operator ] [-Architecture ] [-Context ] [-Credential ] - [-TimeoutSeconds ] + [-TimeoutSeconds ] [-WhatIf] [-Confirm] ``` ## ALIASES @@ -91,6 +91,28 @@ AcceptedValues: [] HelpMessage: '' ``` +### -Confirm + +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +DefaultValue: '' +SupportsWildcards: false +Aliases: +- cf +ParameterSets: +- Name: (All) + Position: Named + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + ### -Context User (default) or System. @@ -247,6 +269,28 @@ AcceptedValues: [] HelpMessage: '' ``` +### -WhatIf + +Says which script would be run as a Win32 requirement script, in which context and architecture, and runs nothing. The command returns nothing. + +```yaml +Type: System.Management.Automation.SwitchParameter +DefaultValue: '' +SupportsWildcards: false +Aliases: +- wi +ParameterSets: +- Name: (All) + Position: Named + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, diff --git a/docs/IntuneScriptLab/Invoke-IntuneWin32AppTest.md b/docs/IntuneScriptLab/Invoke-IntuneWin32AppTest.md index 7865bb0..328ca7e 100644 --- a/docs/IntuneScriptLab/Invoke-IntuneWin32AppTest.md +++ b/docs/IntuneScriptLab/Invoke-IntuneWin32AppTest.md @@ -4,7 +4,7 @@ external help file: IntuneScriptLab-Help.xml HelpUri: https://github.com/fadwen/IntuneScriptLab/blob/main/docs/IntuneScriptLab/Invoke-IntuneWin32AppTest.md Locale: en-US Module Name: IntuneScriptLab -ms.date: 10/05/2026 +ms.date: 11/23/2026 PlatyPS schema version: 2024-05-01 title: Invoke-IntuneWin32AppTest --- @@ -25,7 +25,7 @@ Invoke-IntuneWin32AppTest [[-DetectionPath] ] [[-DetectionRule] ] [[-DependsOn] ] [[-Supersedes] ] [[-Architecture] ] [[-Context] ] [[-Credential] ] [[-InstallContext] ] [[-ReturnCodes] ] [[-TimeoutSeconds] ] - [[-InstallTimeoutSeconds] ] [-EnforceSignatureCheck] [] + [[-InstallTimeoutSeconds] ] [-EnforceSignatureCheck] [-WhatIf] [-Confirm] ``` ## ALIASES @@ -163,6 +163,28 @@ AcceptedValues: [] HelpMessage: '' ``` +### -Confirm + +Prompts you for confirmation before running the cmdlet. + +```yaml +Type: System.Management.Automation.SwitchParameter +DefaultValue: '' +SupportsWildcards: false +Aliases: +- cf +ParameterSets: +- Name: (All) + Position: Named + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + ### -ContentPath The folder that would be packaged as the .intunewin (copied before use; the copy is @@ -507,6 +529,28 @@ AcceptedValues: [] HelpMessage: '' ``` +### -WhatIf + +Says which command line would be run in which content folder, and runs neither it nor the detection. The command returns nothing. + +```yaml +Type: System.Management.Automation.SwitchParameter +DefaultValue: '' +SupportsWildcards: false +Aliases: +- wi +ParameterSets: +- Name: (All) + Position: Named + IsRequired: false + ValueFromPipeline: false + ValueFromPipelineByPropertyName: false + ValueFromRemainingArguments: false +DontShow: false +AcceptedValues: [] +HelpMessage: '' +``` + ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, diff --git a/en-US/IntuneScriptLab-Help.xml b/en-US/IntuneScriptLab-Help.xml index 6b1834c..db36506 100644 --- a/en-US/IntuneScriptLab-Help.xml +++ b/en-US/IntuneScriptLab-Help.xml @@ -1417,9 +1417,32 @@ Nothing on the device is changed. System.Management.Automation.SwitchParameter + + WhatIf + + + System.Management.Automation.SwitchParameter + + + + Confirm + + + System.Management.Automation.SwitchParameter + + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + System.Management.Automation.SwitchParameter + + Force @@ -1470,6 +1493,15 @@ unless -Force is given. System.Management.Automation.SwitchParameter + + WhatIf + + Says which package would be written, and writes nothing. The command returns nothing. + + + System.Management.Automation.SwitchParameter + + @@ -1601,9 +1633,32 @@ CI gate (Examples\Invoke-IntuneScriptGate.ps1 -SarifPath) writes it as part of a System.String + + WhatIf + + + System.Management.Automation.SwitchParameter + + + + Confirm + + + System.Management.Automation.SwitchParameter + + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + System.Management.Automation.SwitchParameter + + Finding @@ -1638,6 +1693,15 @@ A finding outside it gets an absolute file URI with no base. System.String + + WhatIf + + Says which SARIF log would be written and with how many results, and writes nothing. The command returns nothing. + + + System.Management.Automation.SwitchParameter + + @@ -2467,9 +2531,32 @@ Nothing in the tenant is changed. System.Management.Automation.SwitchParameter + + WhatIf + + + System.Management.Automation.SwitchParameter + + + + Confirm + + + System.Management.Automation.SwitchParameter + + + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + System.Management.Automation.SwitchParameter + + Id @@ -2572,6 +2659,15 @@ Faster, and the right choice right after a change. System.Management.Automation.SwitchParameter + + WhatIf + + Reads the tenant and returns the reports, but leaves out the two things the command changes: it creates no report export job, so the device columns of the apps stay empty, and it does not write the file of -MarkdownPath. + + + System.Management.Automation.SwitchParameter + + @@ -2747,6 +2843,20 @@ Test-IntuneScript's IslContextIssue flags statically. System.Management.Automation.SwitchParameter + + WhatIf + + + System.Management.Automation.SwitchParameter + + + + Confirm + + + System.Management.Automation.SwitchParameter + + @@ -2763,6 +2873,15 @@ on the other. System.String + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + System.Management.Automation.SwitchParameter + + Context @@ -2819,6 +2938,15 @@ Intune allows 60 minutes; the default here is 5. System.Int32 + + WhatIf + + Says which script would be run as a Win32 detection script, in which context and architecture, and runs nothing. The command returns nothing. + + + System.Management.Automation.SwitchParameter + + @@ -2971,6 +3099,20 @@ through a scheduled task (elevated session required). System.Int32 + + WhatIf + + + System.Management.Automation.SwitchParameter + + + + Confirm + + + System.Management.Automation.SwitchParameter + + @@ -2984,6 +3126,15 @@ through a scheduled task (elevated session required). System.String + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + System.Management.Automation.SwitchParameter + + Context @@ -3030,6 +3181,15 @@ Intune allows 30 minutes; the default here is 5. System.Int32 + + WhatIf + + Says which script would be run as a platform script, in which context and architecture, and runs nothing. The command returns nothing. + + + System.Management.Automation.SwitchParameter + + @@ -3215,6 +3375,20 @@ rights and is right for packages set to run with the signed-in user's credential System.Int32 + + WhatIf + + + System.Management.Automation.SwitchParameter + + + + Confirm + + + System.Management.Automation.SwitchParameter + + @@ -3228,6 +3402,15 @@ rights and is right for packages set to run with the signed-in user's credential System.String + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + System.Management.Automation.SwitchParameter + + Context @@ -3285,6 +3468,15 @@ Intune allows 60 minutes; the default here is 5. System.Int32 + + WhatIf + + Says which detection script would be run, and which remediation script after it, and runs neither. The command returns nothing. + + + System.Management.Automation.SwitchParameter + + @@ -3466,6 +3658,20 @@ Under Intune the requirement runs before the install and after the detection has System.Int32 + + WhatIf + + + System.Management.Automation.SwitchParameter + + + + Confirm + + + System.Management.Automation.SwitchParameter + + @@ -3482,6 +3688,15 @@ on the other. System.String + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + System.Management.Automation.SwitchParameter + + Context @@ -3559,6 +3774,15 @@ Intune allows 60 minutes; the default here is 5. System.String + + WhatIf + + Says which script would be run as a Win32 requirement script, in which context and architecture, and runs nothing. The command returns nothing. + + + System.Management.Automation.SwitchParameter + + @@ -3832,6 +4056,20 @@ Soft/hard reboot codes count as success but are reported. System.Management.Automation.SwitchParameter + + WhatIf + + + System.Management.Automation.SwitchParameter + + + + Confirm + + + System.Management.Automation.SwitchParameter + + @@ -3845,6 +4083,15 @@ Soft/hard reboot codes count as success but are reported. System.String + + Confirm + + Prompts you for confirmation before running the cmdlet. + + + System.Management.Automation.SwitchParameter + + ContentPath @@ -4020,6 +4267,15 @@ Default 5 minutes (Intune: 60). System.String + + WhatIf + + Says which command line would be run in which content folder, and runs neither it nor the detection. The command returns nothing. + + + System.Management.Automation.SwitchParameter + + From 8127dff736b46acd2a06f71c2d9fb9f4ca1282e2 Mon Sep 17 00:00:00 2001 From: Jeffrey Stuhr <110697945+fadwen@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:45:21 -0800 Subject: [PATCH 2/2] fix(harness): pin -Confirm as well as -WhatIf inside a run The internal operations of the harness passed -WhatIf:$false and no -Confirm:$false. After a caller says Yes to -Confirm, the preference is still Low in the command's scope, and the functions it calls see it. New-Item, Copy-Item and Remove-Item have an impact of Medium, so each of them asked again for the run folder, the copy of the script and the cleanup. A No to the copy started the host on a file that was not there, which is the result this branch exists to prevent. In a session that cannot answer, the prompts failed with the same outcome: exit code -196608 from a script that never ran. The root module now defines $script:IslInternal, a splat of WhatIf = $false and Confirm = $false, and every internal call to a command that asks ShouldProcess passes it: the operations that had only the one pin, the folders, the CSV files and the cleanup of Export-IntuneAgentDiagnostic and Export-IntuneFindingSarif, which had none because they come after those commands' own question, the detections inside a Win32 app flow, and the two Invoke-CimMethod reads in Get-IslLogonSession, which ask for any method. Module.WhatIf.Tests.ps1 checks the rule on the syntax trees, so that the next such call gets both pins, and runs the launch function with a confirm preference of Low in a session that cannot answer. Refs #88 --- CLAUDE.md | 10 ++- IntuneScriptLab.psm1 | 7 ++ Private/Get-IslExportReport.ps1 | 2 +- Private/Get-IslLogonSession.ps1 | 6 +- Private/Invoke-IslProcess.ps1 | 3 +- Private/Invoke-IslScriptRun.ps1 | 11 +-- Public/Export-IntuneAgentDiagnostic.ps1 | 19 ++-- Public/Export-IntuneFindingSarif.ps1 | 2 +- Public/Invoke-IntuneWin32AppTest.ps1 | 12 +-- Public/Test-IntuneDeployedScript.ps1 | 8 +- Tests/Unit/Module.WhatIf.Tests.ps1 | 90 +++++++++++++++++++ .../Unit/Private/Invoke-IslProcess.Tests.ps1 | 7 +- .../Export-IntuneAgentDiagnostic.md | 4 +- en-US/IntuneScriptLab-Help.xml | 2 +- 14 files changed, 145 insertions(+), 38 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index b461563..0461b08 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -187,9 +187,13 @@ complaint came back as the script's result (#88). So the rule has two halves. Th `Invoke-Intune*Test` commands, the two `Export-` commands and `Get-IntuneScriptHealth` declare `SupportsShouldProcess` and ask once, before anything runs or is written, and return nothing when the answer is no. Every internal operation - the run folder, the copy, a work folder, the removal -of a scheduled task - passes `-WhatIf:$false`, and a call from one gated command to another passes -`-Confirm:$false`, so that one run asks once. `Tests/Unit/Module.WhatIf.Tests.ps1` checks the -preview on the disk, with scripts that leave a marker file when they run. +of a scheduled task, a call from one gated command to another - passes both `-WhatIf:$false` and +`-Confirm:$false`, written `@script:IslInternal`, which the root module defines. Both are needed: +after a Yes to `-Confirm` the preference is still `Low` inside the command, so an operation that +pinned only `-WhatIf` asked again, and a No to the copy started the host on a file that was not +there. `Tests/Unit/Module.WhatIf.Tests.ps1` checks the preview on the disk, with scripts that leave +a marker file when they run, and checks on the syntax trees that every call to a command that asks +`ShouldProcess` has both pins. `Invoke-CimMethod` is such a command, for any method. Of the scheduled-task cmdlets only `Unregister-ScheduledTask` has `-WhatIf`. Under a preference the task was registered and started, and then left behind. diff --git a/IntuneScriptLab.psm1 b/IntuneScriptLab.psm1 index 73af996..f78fb1e 100644 --- a/IntuneScriptLab.psm1 +++ b/IntuneScriptLab.psm1 @@ -33,6 +33,13 @@ foreach ($functionFolder in $functionFolders) { } } +# What every internal operation passes to a cmdlet that asks ShouldProcess: a run folder, a copy, +# a work folder, a cleanup. A command that runs a script or writes a report asks its caller once. +# After that neither -WhatIf nor -Confirm, nor a preference in the caller's session, has a say in +# the bookkeeping. With -WhatIf alone pinned, a caller who had said Yes to -Confirm was asked again +# for each of these, and a No to the copy started the host on a file that was not there. +$script:IslInternal = @{ WhatIf = $false; Confirm = $false } + # Rule registry: every Find-* function in Private\Rules is a rule. Test-IntuneScript runs them # in this order so the output reads from "will it run at all" down to "will it report well". $script:RuleOrder = @( diff --git a/Private/Get-IslExportReport.ps1 b/Private/Get-IslExportReport.ps1 index cf4c57e..92cd345 100644 --- a/Private/Get-IslExportReport.ps1 +++ b/Private/Get-IslExportReport.ps1 @@ -79,6 +79,6 @@ function Get-IslExportReport { @($csv | ConvertFrom-Csv) } finally { - Remove-Item -LiteralPath $zip -Force -ErrorAction SilentlyContinue -WhatIf:$false + Remove-Item -LiteralPath $zip -Force -ErrorAction SilentlyContinue @script:IslInternal } } diff --git a/Private/Get-IslLogonSession.ps1 b/Private/Get-IslLogonSession.ps1 index 89491d0..c35032a 100644 --- a/Private/Get-IslLogonSession.ps1 +++ b/Private/Get-IslLogonSession.ps1 @@ -30,8 +30,10 @@ function Get-IslLogonSession { $seen = @{} foreach ($shell in ($shells | Sort-Object -Property SessionId, Name)) { # Either call returns nothing for a process that ended or that this session may not ask about - $owner = Invoke-CimMethod -InputObject $shell -MethodName GetOwner -ErrorAction SilentlyContinue - $ownerSid = Invoke-CimMethod -InputObject $shell -MethodName GetOwnerSid -ErrorAction SilentlyContinue + # Invoke-CimMethod asks ShouldProcess for any method, these two reads included + $methodSplat = @{ InputObject = $shell; ErrorAction = 'SilentlyContinue' } + $owner = Invoke-CimMethod @methodSplat -MethodName GetOwner @script:IslInternal + $ownerSid = Invoke-CimMethod @methodSplat -MethodName GetOwnerSid @script:IslInternal $sid = Get-IslPropertyValue -InputObject $ownerSid -Name 'Sid' $userName = Get-IslPropertyValue -InputObject $owner -Name 'User' if (-not $sid -or -not $userName) { continue } diff --git a/Private/Invoke-IslProcess.ps1 b/Private/Invoke-IslProcess.ps1 index d836315..e9bf60f 100644 --- a/Private/Invoke-IslProcess.ps1 +++ b/Private/Invoke-IslProcess.ps1 @@ -260,8 +260,7 @@ finally { # Of the task cmdlets used here only this one has -WhatIf. Under a preference the # task would be registered and started and then left behind - $unregisterSplat = @{ TaskName = $taskName; Confirm = $false; WhatIf = $false } - Unregister-ScheduledTask @unregisterSplat -ErrorAction SilentlyContinue + Unregister-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue @script:IslInternal } $stopwatch.Stop() $stdout = if (Test-Path -LiteralPath $outFile) { diff --git a/Private/Invoke-IslScriptRun.ps1 b/Private/Invoke-IslScriptRun.ps1 index 35da16b..d2aa5fc 100644 --- a/Private/Invoke-IslScriptRun.ps1 +++ b/Private/Invoke-IslScriptRun.ps1 @@ -63,11 +63,12 @@ function Invoke-IslScriptRun { Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath "IntuneScriptLab\$runId" } # The run folder and the copy are this function's own bookkeeping. The command that asked for - # the run has had its -WhatIf answered before it called; with a preference still in effect - # here, the copy would be skipped and the host started on a file that is not there - $null = New-Item -ItemType Directory -Path $cache -Force -WhatIf:$false + # the run has had its -WhatIf and its -Confirm answered before it called; with a preference + # still in effect here, the copy would be skipped and the host started on a file that is not + # there + $null = New-Item -ItemType Directory -Path $cache -Force @script:IslInternal $scriptCopy = Join-Path -Path $cache -ChildPath "$Phase.ps1" - Copy-Item -LiteralPath $source -Destination $scriptCopy -WhatIf:$false + Copy-Item -LiteralPath $source -Destination $scriptCopy @script:IslInternal try { $processSplat = @{ @@ -86,7 +87,7 @@ function Invoke-IslScriptRun { $run = Invoke-IslProcess @processSplat } finally { - Remove-Item -LiteralPath $cache -Recurse -Force -ErrorAction SilentlyContinue -WhatIf:$false + Remove-Item -LiteralPath $cache -Recurse -Force -ErrorAction SilentlyContinue @script:IslInternal } [pscustomobject]@{ diff --git a/Public/Export-IntuneAgentDiagnostic.ps1 b/Public/Export-IntuneAgentDiagnostic.ps1 index ba452d3..c8143fd 100644 --- a/Public/Export-IntuneAgentDiagnostic.ps1 +++ b/Public/Export-IntuneAgentDiagnostic.ps1 @@ -47,7 +47,8 @@ function Export-IntuneAgentDiagnostic { function Write-Section { param([string]$Relative, [string[]]$Lines) $file = Join-Path -Path $staging -ChildPath $Relative - $null = New-Item -ItemType Directory -Path (Split-Path -Path $file -Parent) -Force + $folder = Split-Path -Path $file -Parent + $null = New-Item -ItemType Directory -Path $folder -Force @script:IslInternal [System.IO.File]::WriteAllLines($file, [string[]]$Lines, $utf8) } @@ -102,14 +103,14 @@ function Export-IntuneAgentDiagnostic { } try { - $null = New-Item -ItemType Directory -Path $staging -Force + $null = New-Item -ItemType Directory -Path $staging -Force @script:IslInternal # Logs $logFiles = @() if (Test-Path -LiteralPath $LogPath -PathType Container) { $logFiles = @(Get-ChildItem -LiteralPath $LogPath -Filter '*.log' -File) $logFolder = Join-Path -Path $staging -ChildPath 'Logs' - $null = New-Item -ItemType Directory -Path $logFolder -Force + $null = New-Item -ItemType Directory -Path $logFolder -Force @script:IslInternal foreach ($file in $logFiles) { $destination = Join-Path -Path $logFolder -ChildPath $file.Name Copy-SharedFile -Source $file.FullName -Destination $destination @@ -168,20 +169,20 @@ function Export-IntuneAgentDiagnostic { # Timeline if (-not $SkipTimeline -and $logFiles.Count) { $timelineFolder = Join-Path -Path $staging -ChildPath 'Timeline' - $null = New-Item -ItemType Directory -Path $timelineFolder -Force + $null = New-Item -ItemType Directory -Path $timelineFolder -Force @script:IslInternal $events = @(Get-IntuneAgentLog -Path $LogPath -Log All | Where-Object Event) $iso = @{ Name = 'Time'; Expression = { $_.Time.ToString('o') } } $eventRows = $events | Select-Object -Property $iso, Log, Event, Detail, Id, Message $csvSplat = @{ NoTypeInformation = $true; Encoding = 'UTF8' } $eventsCsv = Join-Path -Path $timelineFolder -ChildPath 'events.csv' - $eventRows | Export-Csv -LiteralPath $eventsCsv @csvSplat + $eventRows | Export-Csv -LiteralPath $eventsCsv @csvSplat @script:IslInternal $timelines = @(Get-IntuneAgentTimeline -Path $LogPath -Log All) $timelineRows = $timelines | Select-Object -Property Id, Name, Kind, @{ Name = 'Started'; Expression = { $_.Started.ToString('o') } }, @{ Name = 'Ended'; Expression = { $_.Ended.ToString('o') } }, @{ Name = 'Duration'; Expression = { $_.Duration.ToString() } }, Runs, Outcome, Summary $timelinesCsv = Join-Path -Path $timelineFolder -ChildPath 'timelines.csv' - $timelineRows | Export-Csv -LiteralPath $timelinesCsv @csvSplat + $timelineRows | Export-Csv -LiteralPath $timelinesCsv @csvSplat @script:IslInternal $manifest.Add("Timeline: $($events.Count) event(s), $($timelines.Count) timeline(s)") } else { $manifest.Add('Timeline: skipped') } @@ -189,10 +190,10 @@ function Export-IntuneAgentDiagnostic { $manifest.Insert(0, "IntuneScriptLab diagnostic package, $((Get-Date).ToString('yyyy-MM-dd HH:mm:ss'))") Write-Section -Relative 'Manifest.txt' -Lines $manifest - if (Test-Path -LiteralPath $zip) { Remove-Item -LiteralPath $zip -Force } + if (Test-Path -LiteralPath $zip) { Remove-Item -LiteralPath $zip -Force @script:IslInternal } $zipFolder = Split-Path -Path $zip -Parent if ($zipFolder -and -not (Test-Path -LiteralPath $zipFolder)) { - $null = New-Item -ItemType Directory -Path $zipFolder -Force + $null = New-Item -ItemType Directory -Path $zipFolder -Force @script:IslInternal } $entryCount = Compress-Staging -Folder $staging -Destination $zip } @@ -201,7 +202,7 @@ function Export-IntuneAgentDiagnostic { $PSCmdlet.ThrowTerminatingError($_) } finally { - Remove-Item -LiteralPath $staging -Recurse -Force -ErrorAction SilentlyContinue + Remove-Item -LiteralPath $staging -Recurse -Force -ErrorAction SilentlyContinue @script:IslInternal } Write-Verbose "Completed $($MyInvocation.MyCommand.Name): $zip" diff --git a/Public/Export-IntuneFindingSarif.ps1 b/Public/Export-IntuneFindingSarif.ps1 index 9482b90..aa91085 100644 --- a/Public/Export-IntuneFindingSarif.ps1 +++ b/Public/Export-IntuneFindingSarif.ps1 @@ -172,7 +172,7 @@ function Export-IntuneFindingSarif { return } $folder = Split-Path -Path $outFile -Parent - if ($folder) { $null = New-Item -ItemType Directory -Path $folder -Force } + if ($folder) { $null = New-Item -ItemType Directory -Path $folder -Force @script:IslInternal } $json = $log | ConvertTo-Json -Depth 12 [System.IO.File]::WriteAllText($outFile, $json, [System.Text.UTF8Encoding]::new($false)) Write-Verbose "Wrote $($all.Count) result(s) for $($rules.Count) rule(s) to $outFile" diff --git a/Public/Invoke-IntuneWin32AppTest.ps1 b/Public/Invoke-IntuneWin32AppTest.ps1 index a80ea03..c998266 100644 --- a/Public/Invoke-IntuneWin32AppTest.ps1 +++ b/Public/Invoke-IntuneWin32AppTest.ps1 @@ -112,7 +112,6 @@ function Invoke-IntuneWin32AppTest { if (-not $PSCmdlet.ShouldProcess($ContentPath, $action)) { return } - $detectionSplat['Confirm'] = $false $runAs = if ($Credential) { $Credential.UserName } elseif ($Context -eq 'System') { 'NT AUTHORITY\SYSTEM' } @@ -123,7 +122,10 @@ function Invoke-IntuneWin32AppTest { # them must say installed (W32-MULTI-ONEFALSE, W32-MULTI-BOTHTRUE) function Invoke-DetectionPass { param([string]$Phase, [string]$Path, [hashtable[]]$Rule, [string]$Label) - $script = if ($Path) { Invoke-IntuneDetectionTest -Path $Path @detectionSplat } else { $null } + $script = $null + if ($Path) { + $script = Invoke-IntuneDetectionTest -Path $Path @detectionSplat @script:IslInternal + } $rules = @(foreach ($entry in $Rule) { Test-IntuneWin32Rule -Rule $entry -RuleType Detection }) $unmet = @($rules | Where-Object { -not $_.Met }) $detected = ($null -eq $script -or $script.Detected) -and $unmet.Count -eq 0 @@ -179,9 +181,9 @@ function Invoke-IntuneWin32AppTest { Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath "IntuneScriptLab\$runId" } $copy = Join-Path -Path $cache -ChildPath 'content' - $null = New-Item -ItemType Directory -Path $copy -Force -WhatIf:$false + $null = New-Item -ItemType Directory -Path $copy -Force @script:IslInternal $contentItems = Join-Path -Path $source -ChildPath '*' - Copy-Item -Path $contentItems -Destination $copy -Recurse -Force -WhatIf:$false + Copy-Item -Path $contentItems -Destination $copy -Recurse -Force @script:IslInternal if ($Credential) { Grant-IslFolderAccess -Path $cache -Account $Credential.UserName } try { $cmdFolder = if ([Environment]::Is64BitOperatingSystem) { 'SysWOW64' } else { 'System32' } @@ -199,7 +201,7 @@ function Invoke-IntuneWin32AppTest { $run = Invoke-IslProcess @processSplat } finally { - Remove-Item -LiteralPath $cache -Recurse -Force -ErrorAction SilentlyContinue -WhatIf:$false + Remove-Item -LiteralPath $cache -Recurse -Force -ErrorAction SilentlyContinue @script:IslInternal } [pscustomobject]@{ PSTypeName = 'IntuneScriptLab.RunResult' diff --git a/Public/Test-IntuneDeployedScript.ps1 b/Public/Test-IntuneDeployedScript.ps1 index f35281a..7476699 100644 --- a/Public/Test-IntuneDeployedScript.ps1 +++ b/Public/Test-IntuneDeployedScript.ps1 @@ -37,8 +37,8 @@ function Test-IntuneDeployedScript { $workName = "IntuneScriptLab\preflight-$([guid]::NewGuid().ToString('N'))" $workFolder = Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath $workName # The work folder is this command's own: it reads the tenant and changes nothing, so a - # caller's -WhatIf preference has no say in it - $null = New-Item -ItemType Directory -Path $workFolder -Force -WhatIf:$false + # caller's -WhatIf or -Confirm preference has no say in it + $null = New-Item -ItemType Directory -Path $workFolder -Force @script:IslInternal # Mutable state the nested functions share (an assignment inside them would make a local copy) $groupState = @{ Cache = @{}; Blocked = $false } $filterState = @{ Cache = @{}; Blocked = $false } @@ -105,7 +105,7 @@ function Test-IntuneDeployedScript { $policyId = "$(Get-IslPropertyValue -InputObject $Policy -Name 'id')" $safeName = [regex]::Replace($policyName, '[^\w.-]', '_') $folder = Join-Path -Path $workFolder -ChildPath "$PolicyKind\$safeName-$policyId" - $null = New-Item -ItemType Directory -Path $folder -Force -WhatIf:$false + $null = New-Item -ItemType Directory -Path $folder -Force @script:IslInternal $file = Join-Path -Path $folder -ChildPath "$Role.ps1" # Byte for byte: the encoding rule needs to see the BOM, or its absence, as the tenant stores it [System.IO.File]::WriteAllBytes($file, [System.Convert]::FromBase64String($Content)) @@ -449,7 +449,7 @@ function Test-IntuneDeployedScript { } } finally { - Remove-Item -LiteralPath $workFolder -Recurse -Force -ErrorAction SilentlyContinue -WhatIf:$false + Remove-Item -LiteralPath $workFolder -Recurse -Force -ErrorAction SilentlyContinue @script:IslInternal } Write-Verbose "Completed $($MyInvocation.MyCommand.Name)" } diff --git a/Tests/Unit/Module.WhatIf.Tests.ps1 b/Tests/Unit/Module.WhatIf.Tests.ps1 index 9cdaa02..82b2227 100644 --- a/Tests/Unit/Module.WhatIf.Tests.ps1 +++ b/Tests/Unit/Module.WhatIf.Tests.ps1 @@ -169,4 +169,94 @@ Describe 'What -WhatIf does across the module' -Tag 'Unit', 'Contract' { @($underPreference.RuleName | Sort-Object) | Should-BeCollection @($expected.RuleName | Sort-Object) } } + + Context 'Internal operations' { + It 'pins -WhatIf and -Confirm at every call to a command that asks ShouldProcess' { + # A run folder, a copy, a cleanup: none of them is the caller's to preview or to + # confirm. The rule is checked on the syntax trees, so that the next such call gets + # both pins too. A call passes with the module's splat or with both switches written out + $functionType = [System.Management.Automation.Language.FunctionDefinitionAst] + $parser = [System.Management.Automation.Language.Parser] + $trees = foreach ($folder in 'Public', 'Private', 'Private\Rules') { + $folderPath = Join-Path $script:ModuleRoot $folder + foreach ($file in Get-ChildItem -LiteralPath $folderPath -Filter '*.ps1') { + $parser::ParseFile($file.FullName, [ref]$null, [ref]$null) + } + } + # The module's own functions that declare SupportsShouldProcess + $gated = @(foreach ($tree in $trees) { + foreach ($definition in $tree.FindAll({ param($node) $node -is $functionType }, $true)) { + $binding = $definition.Body.ParamBlock.Attributes | + Where-Object { $_.TypeName.Name -eq 'CmdletBinding' } + if ("$($binding.Extent.Text)" -match 'SupportsShouldProcess') { + $definition.Name + } + } + }) + $commandType = [System.Management.Automation.Language.CommandAst] + $calls = foreach ($tree in $trees) { + foreach ($command in $tree.FindAll({ param($node) $node -is $commandType }, $true)) { + $name = $command.GetCommandName() + # ForEach-Object asks only in its member form, which the module does not use + if (-not $name -or $name -eq 'ForEach-Object') { + continue + } + $asks = $name -in $gated + if (-not $asks) { + $resolved = Get-Command -Name $name -ErrorAction SilentlyContinue | Select-Object -First 1 + $parameters = if ($null -ne $resolved) { $resolved.Parameters } else { $null } + $asks = $null -ne $parameters -and $parameters.ContainsKey('WhatIf') + } + if ($asks) { + $source = $command.Extent.Text + $hasSplat = $source -like '*@script:IslInternal*' + $hasBoth = $source -like '*-WhatIf:$false*' -and $source -like '*-Confirm:$false*' + $leaf = Split-Path -Leaf $command.Extent.File + [pscustomobject]@{ + Call = "${leaf}:$($command.Extent.StartLineNumber) $name" + Pinned = $hasSplat -or $hasBoth + } + } + } + } + + # Guards against a scan that found nothing to check + @($calls).Count | Should-BeGreaterThan 20 + @($calls | Where-Object { -not $_.Pinned } | ForEach-Object { $_.Call }) | Should-BeCollection @() + } + + It 'does not ask again inside a run the caller agreed to, in a session that cannot answer' { + # After a Yes to -Confirm the preference is still Low in the command's scope, and the + # functions it calls see it. With only -WhatIf pinned, the run folder and the copy each + # asked again; here, where nobody can answer, they failed, and the host was started on + # a copy that was never made + $probe = New-MarkerScript -Name 'ConfirmLow' + $run = Invoke-CallerScript -Statement @( + "`$result = & (Get-Module IntuneScriptLab) {" + " param(`$Path)" + " `$ConfirmPreference = 'Low'" + " `$runSplat = @{ Path = `$Path; Architecture = 'x86'; Context = 'User'; Phase = 'detect' }" + " Invoke-IslScriptRun @runSplat -TimeoutSeconds 60" + "} '$($probe.Script)'" + "'exit code: ' + `$result.ExitCode" + ) + + $run.ReachedEnd | Should-BeTrue + $run.Output | Should-BeCollection @('exit code: 0') + Test-Path -LiteralPath $probe.Marker | Should-BeTrue + @($run.ErrorId | Where-Object { $_ -like '*ItemCommand' }) | Should-BeCollection @() + } + + It 'runs when the caller declines to be asked, whatever its confirm preference' { + $probe = New-MarkerScript -Name 'ConfirmFalse' + $run = Invoke-CallerScript -Statement @( + "`$ConfirmPreference = 'Low'" + "`$result = @(Invoke-IntuneDetectionTest -Path '$($probe.Script)' -Confirm:`$false)" + "'detected: ' + `$result[0].Detected" + ) + + $run.Output | Should-BeCollection @('detected: True') + Test-Path -LiteralPath $probe.Marker | Should-BeTrue + } + } } diff --git a/Tests/Unit/Private/Invoke-IslProcess.Tests.ps1 b/Tests/Unit/Private/Invoke-IslProcess.Tests.ps1 index ea9fa89..aaacbe0 100644 --- a/Tests/Unit/Private/Invoke-IslProcess.Tests.ps1 +++ b/Tests/Unit/Private/Invoke-IslProcess.Tests.ps1 @@ -150,8 +150,8 @@ Describe 'Invoke-IslProcess' -Tag 'Unit', 'Private' { } It 'removes the task although the caller''s WhatIf preference is on' { - # Of the task cmdlets only Unregister-ScheduledTask has -WhatIf. Under a preference the - # task was registered and started, and then left on the computer + # Of the task cmdlets only Unregister-ScheduledTask has -WhatIf and -Confirm. Under a + # WhatIf preference the task was registered and started, and then left on the computer $parameters = @{ FilePath = 'C:\host\powershell.exe'; Arguments = '-File "x.ps1"' WorkingDirectory = 'C:\Windows\System32' @@ -164,7 +164,8 @@ Describe 'Invoke-IslProcess' -Tag 'Unit', 'Private' { $result.ExitCode | Should-Be 5 Should-Invoke Unregister-ScheduledTask -ModuleName IntuneScriptLab -Exactly -Times 1 -ParameterFilter { - $PesterBoundParameters.ContainsKey('WhatIf') -and -not $WhatIf + $PesterBoundParameters.ContainsKey('WhatIf') -and -not $WhatIf -and + $PesterBoundParameters.ContainsKey('Confirm') -and -not $Confirm } } diff --git a/docs/IntuneScriptLab/Export-IntuneAgentDiagnostic.md b/docs/IntuneScriptLab/Export-IntuneAgentDiagnostic.md index 6302db5..49c6977 100644 --- a/docs/IntuneScriptLab/Export-IntuneAgentDiagnostic.md +++ b/docs/IntuneScriptLab/Export-IntuneAgentDiagnostic.md @@ -1,4 +1,4 @@ ---- +--- document type: cmdlet external help file: IntuneScriptLab-Help.xml HelpUri: https://github.com/fadwen/IntuneScriptLab/blob/main/docs/IntuneScriptLab/Export-IntuneAgentDiagnostic.md @@ -204,7 +204,7 @@ HelpMessage: '' ### -WhatIf -Says which package would be written, and writes nothing. The command returns nothing. +Says which package would be written, and writes nothing. The command returns nothing. A package that exists is refused without -Force before the preview, as a run would refuse it. ```yaml Type: System.Management.Automation.SwitchParameter diff --git a/en-US/IntuneScriptLab-Help.xml b/en-US/IntuneScriptLab-Help.xml index db36506..457c86c 100644 --- a/en-US/IntuneScriptLab-Help.xml +++ b/en-US/IntuneScriptLab-Help.xml @@ -1496,7 +1496,7 @@ unless -Force is given. WhatIf - Says which package would be written, and writes nothing. The command returns nothing. + Says which package would be written, and writes nothing. The command returns nothing. A package that exists is refused without -Force before the preview, as a run would refuse it. System.Management.Automation.SwitchParameter