Repository navigation
feat(harness): preview a run with -WhatIf instead of half-running it - #90
Conversation
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
fadwen
left a comment
There was a problem hiding this comment.
Notes on the lines whose reason the diff does not show.
|
|
||
| # 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)) { |
There was a problem hiding this comment.
The question is asked after the arguments are checked and before the signature check, so a preview reports a bad argument as a run would and reads nothing from the script. The impact is the default, Medium: nothing asks unless the caller passes -Confirm or has lowered $ConfirmPreference. Running somebody's script is a change, but it is the whole purpose of the command, so High would make every unattended use pass -Confirm:$false.
| if (-not $PSCmdlet.ShouldProcess($ContentPath, $action)) { | ||
| return | ||
| } | ||
| $detectionSplat['Confirm'] = $false |
There was a problem hiding this comment.
The flow calls Invoke-IntuneDetectionTest, which asks its own question now. With -Confirm on this command the preference reaches that call, and the caller would be asked again for each detection of a run already agreed to.
| $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 |
There was a problem hiding this comment.
This is the line the defect went through. Under a preference Copy-Item printed what it would do, and the function went on to start the host with -File pointing at the copy that was never made. The public commands answer the preference before they call this function now; the pin is here so that the function does not depend on every caller having done so.
| 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 } |
There was a problem hiding this comment.
Register-ScheduledTask, Start-ScheduledTask and Stop-ScheduledTask have no -WhatIf; Unregister-ScheduledTask has. Under a preference the task was therefore created and run and not removed. Measured on a lab device as SYSTEM: one IntuneScriptLab-* task left behind before this change, none after it.
| 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)) { |
There was a problem hiding this comment.
The install counts of the apps come from a report export job, and creating one is a POST that needs a ReadWrite scope. It is the one write this command makes to the tenant, so -WhatIf leaves it out and the device columns of the apps stay empty, as they do with -SkipRunState. The reads are not asked about: a preview that returned nothing would be of no use here.
| ) | ||
|
|
||
| $run.ReachedEnd | Should-BeTrue | ||
| @($run.Output | Where-Object { $_ -like 'What if:*' }) | Should-BeCollection -Count 1 |
There was a problem hiding this comment.
The preference has to be set where a module function sees it, which is the global scope and not the scope of a test, so this case runs a script in a new process. The What if: line is read from the output of that process because the host writes it; it does not travel on a stream the test could capture in its own session.
fadwen
left a comment
There was a problem hiding this comment.
Verdict: approve after one should-fix.
Reviewed against ai-powershell-standards (FUN-30, FUN-31, MOD-14). Checked in a Linux sandbox with pwsh 7.6.0 and Pester 6.2.0.
Verified
- No regressions (differential run): full unit suites on #89 and on this branch, same seed.
- Passes went from 886 to 896.
- The 4 new failures on Linux are platform-related: a null
$env:WINDIR,Start-Process -WindowStyle, andGet-AuthenticodeSignature, which Linux doesn't have. - No test that passed on #89 fails here.
- The five
Invoke-Intune*Testcommands: each asks once, after its arguments are checked and before anything runs. Invoke-IntuneDetectionTest: asks per pipeline item, inprocess.Invoke-IntuneWin32AppTest: passesConfirm = $falseto its inner detections.- The two export commands: each gates its file write.
Get-IntuneScriptHealth: gates only the export job and the Markdown file, and still returns its reports. The note on FUN-31 is reasonable.- Internal bookkeeping: the run folder, the copy, the content copy, the work folder, the zip cleanup and
Unregister-ScheduledTaskall pass-WhatIf:$false. This also closes the follow-up I raised on #87 about the scheduled-task path.
Unverified (needs Windows, a lab device or CI): the lab device run as SYSTEM, and CI run 45275762545 (this PR has no checks because its base isn't main).
Should-fix: under -Confirm, the internal file operations prompt as well and can bring back the #88 defect
-Confirmsets$ConfirmPreference = 'Low'in the command's scope, and the module's private functions see it. So do a global$ConfirmPreference = 'Low'and the cmdlets they call.- The bookkeeping calls pass
-WhatIf:$falsebut not-Confirm:$false:Invoke-IslScriptRun:New-Item,Copy-ItemandRemove-Item.Invoke-IntuneWin32AppTest: the contentNew-Item,Copy-ItemandRemove-Item.Test-IntuneDeployedScript: the work folder.Get-IslExportReport: the zip cleanup.
- Reproduced: a function that, with
$ConfirmPreference = 'Low', callsNew-Item -ItemType Directory -Force -WhatIf:$falseprompts. Under-NonInteractiveit fails with "PowerShell is in NonInteractive mode". - So
Invoke-IntuneDetectionTest -Confirmasks once for the run, then again for the folder, the copy and the cleanup. Answering No to the copy starts the host on a file that isn't there, which is the #88 symptom. Unregister-ScheduledTaskandStop-IslProcessTreealready passConfirm = $false. Do the same at the other sites (-Confirm:$false -WhatIf:$false).- Add a case to
Module.WhatIf.Tests.ps1that runs one command with$ConfirmPreference = 'Low'and-Confirm:$falseon the outer call. The fixture's marker shows it ran, and nothing prompted, in a-NonInteractivechild.
Nits
- The CLAUDE.md rule could read "internal operations pass
-WhatIf:$false -Confirm:$false", so that the next new site gets both. Export-IntuneAgentDiagnostic: the "exists, use -Force" check comes beforeShouldProcess. So-WhatIfon an existing zip without-Forceerrors instead of previewing. That's defensible (the real run would fail too), but say so in the help's-WhatIftext.
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
|
The should-fix and both nits are addressed in 8127dff.
The test, and one difference from the review.
Nits
The checks that could not be made in the sandbox
|
fadwen
left a comment
There was a problem hiding this comment.
Re-review after 8127dff and 07f7f5f. Verdict: approve. The should-fix and both nits are resolved.
Verified (Linux sandbox, pwsh 7.6.0, Pester 6.2.0)
$script:IslInternal: defined in the root module as@{ WhatIf = $false; Confirm = $false }, and@script:IslInternalsplats correctly. Inside the module, with$ConfirmPreference = 'Low'and$WhatIfPreference = $truein a-NonInteractivesession,New-Item … @script:IslInternalcreated the folder without prompting.- The AST rule test catches a missing pin: I replaced the splat in
Get-IslExportReportwith-WhatIf:$falsealone. "pins -WhatIf and -Confirm at every call…" then failed and namedGet-IslExportReport.ps1:82 Remove-Item. With the splat restored it passes. - Coverage beyond the sites I named: both export commands' folders, CSV files and cleanup;
Invoke-CimMethodinGet-IslLogonSession; and the inner detections of the Win32 flow. A good catch onInvoke-CimMethod. - No regressions (differential run): full unit suites on the previous head (7747fb8) and on this one, same seed.
- Passes went from 896 to 901.
- 07f7f5f lets 4 error-flow tests and the Timeline container pass on Linux now.
- Of the 2 new Linux failures, both new behaviour tests need a Windows host to launch the script (empty exit code,
detected: False). They are not logic failures.
- CI on this PR: run 45282671206 passed all five jobs.
My test suggestion was wrong, and your correction is right: -Confirm:$false on the outer call sets the preference to None for everything it calls. So that case passed before the fix, and the right failing case is the state after a Yes to -Confirm, which your child-process test covers.
Unverified: the lab device run as SYSTEM (137 passed).
Summary
With
$WhatIfPreferenceset in the caller's session, the runtime harness neither previewed a run nor made it. None of its commands declaredSupportsShouldProcess, so the preference went straight to the cmdlets they call: the copy of the script was skipped, the host was started on the file that was not there, and its complaint came back as the result of the script. The owner's decision on #88 is that-WhatIfpreviews a run. This change does that, and makes sure nothing inside the module consults the preference. Closes #88.This pull request is stacked on #89 (
fix/terminating-errors) and merges after it.Changes
Invoke-Intune*Testcommands declareSupportsShouldProcessand ask once, after their arguments are checked and before anything runs. Under-WhatIfor a preference they say which script or command line they would run, in which context and architecture, run nothing and return nothing.Invoke-IntuneDetectionTestasks for each script that arrives on the pipeline.Export-IntuneAgentDiagnosticandExport-IntuneFindingSarifask before they write their file, and return nothing when the answer is no.Get-IntuneScriptHealthstill reads the tenant and returns its reports under-WhatIf. It asks for the two things it changes: the report export job it creates in the tenant for the app install counts, and the file of-MarkdownPath.-WhatIf:$falseand-Confirm:$false, written@script:IslInternal, a splat the root module defines: the run folder and the copy of the script inInvoke-IslScriptRun, the content copy ofInvoke-IntuneWin32AppTestand its inner detections, the work folder ofTest-IntuneDeployedScript, the downloaded zip inGet-IslExportReport,Unregister-ScheduledTaskinInvoke-IslProcess, the folders, the CSV files and the cleanup of the two export commands, and the twoInvoke-CimMethodreads inGet-IslLogonSession. Both are needed: after a Yes to-Confirmthe preference is stillLowinside the command, and an operation that pinned only-WhatIfasked again.Tests/Unit/Module.WhatIf.Tests.ps1. Its scripts leave a marker file when they run, so "ran nothing" is checked on the disk. It covers each of the five commands, pipeline input, the two export commands, a preference set in a calling script, and a command that only reads. It also checks on the syntax trees that every call in the module to a command that has-WhatIfcarries both pins, and runs the launch function under a confirm preference ofLowin a session that cannot answer.-WhatIfand-Confirm, each-WhatIfwith what that command says and leaves out, and the compiled help is rebuilt.README.md,CHANGELOG.mdandCLAUDE.mdhave the behaviour and the rule.Verification
presentand exits 0, on PowerShell 7.6.10 and Windows PowerShell 5.1: after$global:WhatIfPreference = $true,Invoke-IntuneDetectionTestreturned exit code -196608 and the host'sThe argument '...\detect.ps1' to the -File parameter does not exist.With this change it returns nothing, and the script does not run.NT AUTHORITY\SYSTEMunder Windows PowerShell 5.1.26100.9818,Invoke-IntunePlatformScriptTest -Context Systemwith the preference set. Without this change: the command ended with an error and oneIntuneScriptLab-*scheduled task was left registered. With it: nothing ran, nothing was returned, and no task was left. Of the scheduled-task cmdlets onlyUnregister-ScheduledTaskhas-WhatIf../Tests/Invoke-Tests.ps1 -CodeCoverageon PowerShell 7.6.10: 1,105 passed, 3 failed, 7 skipped, coverage 95.37 percent../Tests/Invoke-Tests.ps1on Windows PowerShell 5.1: 1,069 passed, 3 failed, 43 skipped. The three failures are the ones that fail on that computer without this change and pass in CI (Repair-IntuneScript corrupts an ANSI script on a host with a UTF-8 system code page #75 twice, In-box module table does not list UOPProviders, present on Windows 11 26H2 #76).Invoke-ScriptAnalyzerat Error and Warning on the 16 changed script files: no findings.Test-StandardsCompliance.ps1of ai-powershell-standards 2.0.0 on the new test file: no findings../Build/Build-Help.ps1and./Build/Publish-Module.ps1 -WhatIf: the help builds with no placeholder left, and the staged module imports and serves its help.-Confirm: every suite locally, 1,108 passed on PowerShell 7.6.10 with 95.37 percent coverage and 1,072 on Windows PowerShell 5.1, with the same three failures; on the lab device as SYSTEM, the integration suites and the tests of the launch path, 137 passed and 0 failed, with no scheduled task left.quality-gates.yml, dispatched on this branch because it triggers only for pull requests intomain, run 45275762545: all five jobs passed, among them thehelpjob, which compares the rebuilt help with the committed file. After the change for-Confirm, run 45282671206: all five jobs passed.Notes
Get-IntuneScriptHealthis aGet-command that declaresSupportsShouldProcess. FUN-31 rules that out for a read-only function; this one creates an export job in the tenant and can write a file, and those two are what it asks about.Test-IntuneDeployedScriptandCompare-IntuneDeployedScriptchange nothing and declare nothing. They work with a preference as without one, which the tests check for the first.ms.datein all 26 Markdown files, in a format that follows the culture of the computer (Help Markdown: examples are not fenced and parameter drift is not gated (PLT-05, PLT-09) #68). Only the eight files whose parameters changed are in this change, with the date in the format of the others.Confirmtext in the help is the standard sentence PlatyPS writes.