Skip to content
Open
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
15 changes: 9 additions & 6 deletions .github/workflows/quality-gates.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
# tests Windows, PowerShell 7. PSScriptAnalyzer at Error and Warning over the module, the
# kit and the tests, the 115-character line limit, then the whole Pester suite (the
# module's unit and integration suites and the validation kit's unit suite) with an
# 80% coverage gate over Public/ and Private/. Nothing here
# reaches a tenant: every Graph call in the suites goes through the mocked
# Invoke-IslGraphRequest seam, and the suites that need an elevated session, a lab
# account or a Graph connection skip themselves.
# 80% coverage gate over Public/ and Private/. Nothing here reaches a tenant: every
# Graph call in the suites goes through the mocked Invoke-IslGraphRequest seam, and
# the suites that need a lab account or a Graph connection skip themselves. The
# hosted Windows runner is elevated, so the SYSTEM-context tests run: they register
# scheduled tasks named IntuneScriptLab-* as NT AUTHORITY\SYSTEM on the runner, run
# a script through each and remove them.
#
# Every Pester run goes through Tests/Invoke-Tests.ps1, the script a developer runs as well. It
# shuffles the order, so a test that only passes because of what ran before it fails here
Expand Down Expand Up @@ -185,8 +187,9 @@ jobs:
"Pester $((Get-Module Pester).Version) on PowerShell $($PSVersionTable.PSVersion)" | Write-Host

# The integration suite as well: it launches the 5.1 hosts the harness uses on a device.
# The hosted runner's token is not elevated (IsInRole Administrator is false), so the
# SYSTEM-context tests skip here as they do under pwsh; they run on the lab devices
# The hosted runner is elevated, so the SYSTEM-context tests run here as they do under
# pwsh: they register and remove IntuneScriptLab-* scheduled tasks as SYSTEM on the runner.
# The user-context suite needs a lab account and skips itself.
- name: Pester under Windows PowerShell 5.1
shell: powershell
run: |
Expand Down
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,17 @@ 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.
- 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
process that is already gone on its error stream, and 5.1 made a terminating error of that
line. The process tree is now ended without that stream reaching PowerShell as errors, and a
warning is written when a process could not be ended.
- Four tests were skipped on every run: the three of the SYSTEM-context integration suite, which
are the only ones that launch a script through a scheduled task as SYSTEM, and the file-version
test of `Test-IntuneWin32Rule`. Their skip condition read a variable that was set only after
Pester had evaluated the condition. It is decided during discovery now, so the SYSTEM-context
suite runs in an elevated session and is skipped in any other.

## [0.34.0] - 2026-10-15

Expand Down
11 changes: 9 additions & 2 deletions Private/Invoke-IslProcess.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,10 @@
$stderrTask = $process.StandardError.ReadToEndAsync()
if (-not $process.WaitForExit($TimeoutSeconds * 1000)) {
$timedOut = $true
& taskkill.exe /PID $process.Id /T /F 2>&1 | Out-Null
# The cleanup is not the caller's to preview or confirm. A function of this module
# sees a global $WhatIfPreference, and under it the tree would stay and the wait
# below would not end
Stop-IslProcessTree -ProcessId $process.Id -Confirm:$false -WhatIf:$false
$process.WaitForExit()
}
$stopwatch.Stop()
Expand Down Expand Up @@ -236,9 +239,13 @@
Filter = "CommandLine LIKE '%$runId%'"
ErrorAction = 'SilentlyContinue'
}
# Stopping the task has usually ended some of them, and ending one ends its
# children, so a later id in the list is often gone already
Get-CimInstance @cimInstanceSplat |
Where-Object { $_.ProcessId -ne $PID } |
ForEach-Object { & taskkill.exe /PID $_.ProcessId /T /F 2>&1 | Out-Null }
ForEach-Object {
Stop-IslProcessTree -ProcessId $_.ProcessId -Confirm:$false -WhatIf:$false
}
}
else {
# cmd writes the exit file before its own redirections are flushed; give it a moment
Expand Down
83 changes: 83 additions & 0 deletions Private/Stop-IslProcessTree.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
function Stop-IslProcessTree {
<#
.SYNOPSIS
Ends a process and every process it started.

.DESCRIPTION
The cleanup after a run that timed out. taskkill.exe ends the tree, and it is started as a
process whose streams .NET redirects, not with the call operator: Windows PowerShell 5.1
turns a line that a native command writes to a redirected error stream into an error record,
and with an error preference of Stop in the caller's scope that record ends the command. A
process that is already gone is such a line ("The process ... not found", exit code 128), and
it is the state the cleanup wants.

Nothing is reported when taskkill succeeds or finds no such process. When it fails for
another reason and the process is still there, a warning says so, because then the run left
something behind.

.PARAMETER ProcessId
The id of the process at the root of the tree.

.EXAMPLE
Stop-IslProcessTree -ProcessId $process.Id -Confirm:$false -WhatIf:$false

Ends the process a run started, and what that process started, after the run timed out. The
two switches keep the caller's preferences out of it: the cleanup has to happen.

.EXAMPLE
Stop-IslProcessTree -ProcessId 4711 -WhatIf

Says which process tree would be ended, and ends nothing.

.INPUTS
None.

.OUTPUTS
None.
#>
[CmdletBinding(SupportsShouldProcess)]
[OutputType([void])]
param(
[Parameter(Mandatory)]
[int]$ProcessId
)

if (-not $PSCmdlet.ShouldProcess("process $ProcessId and the processes it started", 'End')) {
return
}

$startInfo = [System.Diagnostics.ProcessStartInfo]::new()
$startInfo.FileName = Join-Path -Path ([System.Environment]::SystemDirectory) -ChildPath 'taskkill.exe'
$startInfo.Arguments = "/PID $ProcessId /T /F"
$startInfo.UseShellExecute = $false
$startInfo.CreateNoWindow = $true
$startInfo.RedirectStandardOutput = $true
$startInfo.RedirectStandardError = $true
$taskkill = [System.Diagnostics.Process]::new()
$taskkill.StartInfo = $startInfo
try {
$null = $taskkill.Start()
# Both streams are read while the process runs, so that neither fills and blocks it
$outputTask = $taskkill.StandardOutput.ReadToEndAsync()
$errorTask = $taskkill.StandardError.ReadToEndAsync()
$taskkill.WaitForExit()
$exitCode = $taskkill.ExitCode
$null = $outputTask.GetAwaiter().GetResult()
$errorText = "$($errorTask.GetAwaiter().GetResult())".Trim()
} catch {
$PSCmdlet.ThrowTerminatingError($_)
} finally {
$taskkill.Dispose()
}

Write-Verbose "taskkill.exe /PID $ProcessId /T /F ended with exit code $exitCode. $errorText"
# 0 is success and 128 is "no such process". After any other answer the process itself decides:
# taskkill also fails when a child ended between its listing of the tree and its attempt
if ($exitCode -notin 0, 128) {
$survivor = Get-Process -Id $ProcessId -ErrorAction SilentlyContinue
if ($null -ne $survivor) {
Write-Warning ("Process $ProcessId is still running: taskkill.exe ended with exit code " +
"${exitCode}. $errorText")
}
}
}
11 changes: 8 additions & 3 deletions Tests/Integration/SystemContext.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,18 @@

#pester:no-parallel

BeforeDiscovery {
# Pester evaluates -Skip during discovery, before any BeforeAll runs. Set there, this was still
# unset when the conditions read it, and the tests were skipped in an elevated session too
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$script:IsAdmin = ([Security.Principal.WindowsPrincipal]$identity).IsInRole(
[Security.Principal.WindowsBuiltInRole]::Administrator)
}

BeforeAll {
$script:ModuleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') -Force
. (Join-Path $script:ModuleRoot 'Tests\TestHelpers\TestHelpers.ps1')
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$script:IsAdmin = ([Security.Principal.WindowsPrincipal]$identity).IsInRole(
[Security.Principal.WindowsBuiltInRole]::Administrator)
}

AfterAll {
Expand Down
163 changes: 163 additions & 0 deletions Tests/Unit/Private/Stop-IslProcessTree.Tests.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' }

<#
The cleanup after a run that timed out, against real processes: a cmd.exe that runs ping.exe is
the tree. The case that matters most is the process that is already gone, under an error
preference of Stop: on Windows PowerShell 5.1 the call-operator form of this cleanup ended the
caller with taskkill's "not found" line.
#>

BeforeAll {
if (-not (Get-Module -Name IntuneScriptLab)) {
$moduleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot))
Import-Module (Join-Path $moduleRoot 'IntuneScriptLab.psd1')
}

function Start-TestProcessTree {
<#
.SYNOPSIS
Starts cmd.exe running ping.exe for two minutes and returns the ids of both.
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',
Justification = 'Starts two short-lived processes that the test ends itself.')]
[CmdletBinding()]
[OutputType([int[]])]
param()

$startParameters = @{
FilePath = Join-Path -Path $env:WINDIR -ChildPath 'System32\cmd.exe'
ArgumentList = '/d', '/c', 'ping.exe -n 120 127.0.0.1 > nul'
WindowStyle = 'Hidden'
PassThru = $true
}
$parent = Start-Process @startParameters
$child = $null
$deadline = (Get-Date).AddSeconds(15)
while ($null -eq $child -and (Get-Date) -lt $deadline) {
Start-Sleep -Milliseconds 200
$child = Get-CimInstance -ClassName Win32_Process -Filter "ParentProcessId = $($parent.Id)" |
Where-Object { $_.Name -eq 'PING.EXE' } | Select-Object -First 1
}
if ($null -eq $child) {
$exception = [System.TimeoutException]::new('cmd.exe did not start ping.exe within 15 seconds.')
$category = [System.Management.Automation.ErrorCategory]::OperationTimeout
$errorRecord = [System.Management.Automation.ErrorRecord]::new(
$exception, 'ChildProcessNotStarted', $category, $parent.Id)
$PSCmdlet.ThrowTerminatingError($errorRecord)
}
$parent.Id, [int]$child.ProcessId
}

function Wait-ProcessGone {
<#
.SYNOPSIS
Waits up to ten seconds for the processes to end and returns the ids still running.
#>
[CmdletBinding()]
[OutputType([int[]])]
param(
[Parameter(Mandatory)]
[int[]]$Id
)

$deadline = (Get-Date).AddSeconds(10)
do {
$running = @(Get-Process -Id $Id -ErrorAction SilentlyContinue | ForEach-Object { $_.Id })
if ($running.Count -gt 0) {
Start-Sleep -Milliseconds 200
}
} while ($running.Count -gt 0 -and (Get-Date) -lt $deadline)
$running
}
}

Describe 'Stop-IslProcessTree' -Tag 'Unit', 'Private' {

Context 'Parameter Validation' {
It 'declares ProcessId as mandatory and supports -WhatIf' {
InModuleScope IntuneScriptLab {
$command = Get-Command -Name Stop-IslProcessTree
$command | Should-HaveParameter -ParameterName 'ProcessId' -Type ([int]) -Mandatory
$command | Should-HaveParameter -ParameterName 'WhatIf'
}
}
}

Context 'Core Functionality' {
It 'ends the process and the process it started' {
$tree = @(Start-TestProcessTree)
try {
InModuleScope IntuneScriptLab -Parameters @{ ProcessId = $tree[0] } {
Stop-IslProcessTree -ProcessId $ProcessId -Confirm:$false -ErrorAction Stop
}

@(Wait-ProcessGone -Id $tree) | Should-BeCollection @()
} finally {
Get-Process -Id $tree -ErrorAction SilentlyContinue | Stop-Process -Force
}
}

It 'ends nothing under -WhatIf' {
$tree = @(Start-TestProcessTree)
try {
InModuleScope IntuneScriptLab -Parameters @{ ProcessId = $tree[0] } {
Stop-IslProcessTree -ProcessId $ProcessId -WhatIf
}

@(Get-Process -Id $tree -ErrorAction SilentlyContinue).Count | Should-Be 2
} finally {
Get-Process -Id $tree -ErrorAction SilentlyContinue | Stop-Process -Force
}
}
}

Context 'Error Handling' {
It 'neither fails nor warns for a process that is already gone, under an error preference of Stop' {
$tree = @(Start-TestProcessTree)
Get-Process -Id $tree -ErrorAction SilentlyContinue | Stop-Process -Force
@(Wait-ProcessGone -Id $tree) | Should-BeCollection @()

InModuleScope IntuneScriptLab -Parameters @{ ProcessId = $tree[0] } {
# The preference a CI step and a script started with -File give the module
$ErrorActionPreference = 'Stop'
$warnings = @()
Stop-IslProcessTree -ProcessId $ProcessId -Confirm:$false -WarningVariable warnings 3>$null
$warnings.Count | Should-Be 0
}
}

It 'ends a timed-out run although the caller''s WhatIf preference is on' {
# A module function sees a global $WhatIfPreference. If the cleanup obeyed it, the process
# would go on, and the run would wait for it: here for the half minute that ping takes
$parameters = @{
FilePath = Join-Path -Path $env:WINDIR -ChildPath 'System32\cmd.exe'
Arguments = '/d /c ping.exe -n 30 127.0.0.1 > nul'
WorkingDirectory = $TestDrive
WorkFolder = $TestDrive
TimeoutSeconds = 2
}
InModuleScope IntuneScriptLab -Parameters @{ Parameters = $parameters } {
$WhatIfPreference = $true
$result = Invoke-IslProcess @Parameters
$result.TimedOut | Should-BeTrue
$result.Duration.TotalSeconds | Should-BeLessThan 15
}
}

It 'lets a timed-out run end with its result under an error preference of Stop' {
$parameters = @{
FilePath = Join-Path -Path $env:WINDIR -ChildPath 'System32\cmd.exe'
Arguments = '/d /c ping.exe -n 120 127.0.0.1 > nul'
WorkingDirectory = $TestDrive
WorkFolder = $TestDrive
TimeoutSeconds = 2
}
InModuleScope IntuneScriptLab -Parameters @{ Parameters = $parameters } {
$ErrorActionPreference = 'Stop'
$result = Invoke-IslProcess @Parameters
$result.TimedOut | Should-BeTrue
$result.ExitCode | Should-BeNull
}
}
}
}
7 changes: 7 additions & 0 deletions Tests/Unit/Public/Test-IntuneWin32Rule.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,13 @@
afterwards; the 32-bit registry view is read from a Windows value that differs between views.
#>

BeforeDiscovery {
# Pester evaluates -Skip during discovery, before any BeforeAll runs, so the condition of the
# file-version test is decided here. BeforeAll looks again, because a variable set during
# discovery does not reach the run
$script:HasVersioned = Test-Path -LiteralPath (Join-Path $env:WINDIR 'System32\notepad.exe')
}

BeforeAll {
$script:ModuleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $PSScriptRoot))
Import-Module (Join-Path $script:ModuleRoot 'IntuneScriptLab.psd1') -Force
Expand Down