Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
20 changes: 20 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,26 @@ 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, 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.

### `$WhatIfPreference` is inherited by child scopes

Under `Publish-Module.ps1 -WhatIf`, the preference reaches the staging cmdlets and `Build-Help.ps1`.
Expand Down
7 changes: 7 additions & 0 deletions IntuneScriptLab.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -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 = @(
Expand Down
2 changes: 1 addition & 1 deletion Private/Get-IslExportReport.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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 @script:IslInternal
}
}
6 changes: 4 additions & 2 deletions Private/Get-IslLogonSession.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
4 changes: 3 additions & 1 deletion Private/Invoke-IslProcess.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,9 @@
}
}
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
Unregister-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue @script:IslInternal
}
$stopwatch.Stop()
$stdout = if (Test-Path -LiteralPath $outFile) {
Expand Down
10 changes: 7 additions & 3 deletions Private/Invoke-IslScriptRun.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,13 @@ 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 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
Copy-Item -LiteralPath $source -Destination $scriptCopy @script:IslInternal

try {
$processSplat = @{
Expand All @@ -83,7 +87,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 @script:IslInternal
}

[pscustomobject]@{
Expand Down
24 changes: 14 additions & 10 deletions Public/Export-IntuneAgentDiagnostic.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -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'
Expand All @@ -44,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)
}

Expand Down Expand Up @@ -99,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
Expand Down Expand Up @@ -165,31 +169,31 @@ 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') }

$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
}
Expand All @@ -198,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"
Expand Down
7 changes: 5 additions & 2 deletions Public/Export-IntuneFindingSarif.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -168,8 +168,11 @@ 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 }
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"
Expand Down
17 changes: 13 additions & 4 deletions Public/Get-IntuneScriptHealth.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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')]
Expand Down Expand Up @@ -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)) {

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

try {
foreach ($row in @(Get-IslExportReport -ReportName 'AppInstallStatusAggregate')) {
$appInstall["$(Get-IslPropertyValue -InputObject $row -Name 'ApplicationId')"] = $row
Expand Down Expand Up @@ -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')
Expand All @@ -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"
}
Expand Down
8 changes: 7 additions & 1 deletion Public/Invoke-IntuneDetectionTest.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -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)) {

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

return
}

$reasons = [System.Collections.Generic.List[string]]::new()
$signatureStatus = ''
$run = $null
Expand Down
8 changes: 7 additions & 1 deletion Public/Invoke-IntunePlatformScriptTest.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -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' }

Expand Down
13 changes: 12 additions & 1 deletion Public/Invoke-IntuneRemediationTest.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -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
Expand Down
Loading