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
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,15 @@ entries are carried over from the manifest's release notes.
without the key.
- CI installs Pester 6.2.0 and PSScriptAnalyzer 1.25.0 exactly, where it took any Pester 6 from
6.2.0 on and the newest PSScriptAnalyzer.
- The module's functions run under strict mode, set once in the root module. A read of a variable
that was never assigned, or of a member that is not there, is an error where it was a silent
`$null`. Graph replies, export rows and the other data with optional members are read through one
private accessor that takes a dictionary and an object alike, so a reply that leaves out an
optional field, such as a policy without a run schedule or a remediation script, is read as
before.
- Importing the module fails when its `Private`, `Private\Rules` or `Public` folder is missing or
when one of their files fails to load. A file that did not parse wrote an error and left the
module imported without the commands of that file.

### Removed

Expand Down
27 changes: 25 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,28 @@ always false. Name locals so they cannot collide with a parameter, and capture w
function needs from `$PSBoundParameters` into a plain variable before defining it. 0.26.0 fixed
both, with tests.

### The module runs under strict mode, and optional members are read through one accessor

`IntuneScriptLab.psm1` sets `Set-StrictMode -Version Latest`, so in every function a read of a
member that is not there is a terminating error: `$reply.runSchedule` on a Graph reply without a
schedule, `$table.Severity` on a settings table without that key, `$result.Sid` on a CIM call that
returned nothing. A hashtable the module's own caller wrote is read with an index
(`$Rule['Operator']`), which gives `$null` for a missing key. Everything that comes from outside -
a Graph reply, an export row, a CIM result, an object that has one of two shapes - is read with
`Get-IslPropertyValue`, which returns nothing for a missing input, key or property and works for a
dictionary and an object alike. `Invoke-MgGraphRequest` returns dictionaries and a recorded fixture
read with `ConvertFrom-Json` returns objects, so member syntax that passes against one can fail
against the other.

Code inside `InModuleScope` runs under the module's strict mode too. A mock body does not: it
stays in the test file's scope, where it can also call the helpers in `Tests/TestHelpers`. A fake
of a run result goes through `ConvertTo-FakeRunResult`, so that it has every member the real one
has.

The loader fails the import when `Private`, `Private/Rules` or `Public` is missing or a file in
them fails to load. A file that does not parse used to leave the module imported without its
commands.

### A nested function returning `@()` hands the caller `$null`

Several public commands use nested helper functions. PowerShell unrolls an empty array on the
Expand Down Expand Up @@ -175,5 +197,6 @@ under Windows PowerShell 5.1 as well before pushing:
powershell -NoProfile -File ./Tests/Invoke-Tests.ps1 -TestType Unit
```

The script sets strict mode for itself and turns it off around the Pester run, because the suites,
the validation kit and the module are not written for strict mode yet. Remove that when they are.
The script sets strict mode for itself and turns it off around the Pester run, because the suites
and the validation kit are not written for strict mode yet. Remove that when they are. The module
does not depend on it: it sets its own strict mode in the root module.
37 changes: 23 additions & 14 deletions IntuneScriptLab.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,32 @@
# detection/remediation scripts, platform scripts and Win32 app detection/requirement scripts.
# Every rule is backed by an observation in ..\Validation\Findings.md rather than by the docs.

$ModuleRoot = $PSScriptRoot
Write-Verbose "Initializing IntuneScriptLab module from: $ModuleRoot"
Set-StrictMode -Version Latest

# Import Private functions (helpers first, then the rules that use them)
foreach ($folder in 'Private', 'Private\Rules') {
$functions = Get-ChildItem -Path "$ModuleRoot\$folder\*.ps1" -ErrorAction SilentlyContinue
foreach ($function in $functions) {
Write-Verbose "Loading private function: $($function.Name)"
. $function.FullName
# Private helpers first, then the rules that use them, then the public functions. A folder that
# is missing or a file that fails to load fails the import: without that the module would import
# with commands missing.
$privateFolder = Join-Path -Path $PSScriptRoot -ChildPath 'Private'
$functionFolders = @(
$privateFolder
(Join-Path -Path $privateFolder -ChildPath 'Rules')
(Join-Path -Path $PSScriptRoot -ChildPath 'Public')
)
foreach ($functionFolder in $functionFolders) {
if (-not (Test-Path -LiteralPath $functionFolder -PathType Container)) {
throw "The module folder '$functionFolder' is missing."
}
}

# Import Public functions
$publicFunctions = Get-ChildItem -Path "$ModuleRoot\Public\*.ps1" -ErrorAction SilentlyContinue
foreach ($function in $publicFunctions) {
Write-Verbose "Loading public function: $($function.Name)"
. $function.FullName
foreach ($functionFile in Get-ChildItem -LiteralPath $functionFolder -Filter '*.ps1' -File) {
try {
Write-Verbose "Loading $($functionFile.FullName)"
. $functionFile.FullName
} catch {

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 catch that only rethrows is what makes a file that does not parse fail the import. Dot-sourcing such a file raises an error that ends only that statement, so without the try the loop went on and the module imported without the commands of the file. Rethrown from catch, the error ends the root module. Module.Contract.Tests.ps1 imports a copy with such a file in a new process and checks that the module is not loaded afterwards.

# Not dead code: an error in a dot-sourced file, such as one that does not parse, ends
# only that statement. Rethrown here it ends the root module, and so the import.
throw
}
}
}

# Rule registry: every Find-* function in Private\Rules is a rule. Test-IntuneScript runs them
Expand Down
38 changes: 19 additions & 19 deletions Private/ConvertFrom-IslRuleSpec.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ function ConvertFrom-IslRuleSpec {
[hashtable]$Rule
)

$kind = if ($Rule.Type) { "$($Rule.Type)" }
elseif ($Rule.'@odata.type' -match '(?i)win32LobApp(FileSystem|Registry|ProductCode|PowerShellScript)') {
$kind = if ($Rule['Type']) { "$($Rule['Type'])" }
elseif ($Rule['@odata.type'] -match '(?i)win32LobApp(FileSystem|Registry|ProductCode|PowerShellScript)') {
switch ($Matches[1].ToLower()) {
'filesystem' { 'File' }
'registry' { 'Registry' }
Expand All @@ -38,32 +38,32 @@ function ConvertFrom-IslRuleSpec {
else { '' }

$splat = @{}
$operator = if ($Rule.Operator) { "$($Rule.Operator)" } else { '' }
$value = if ($null -ne $Rule.ComparisonValue) { "$($Rule.ComparisonValue)" }
elseif ($null -ne $Rule.Value) { "$($Rule.Value)" }
$operator = if ($Rule['Operator']) { "$($Rule['Operator'])" } else { '' }
$value = if ($null -ne $Rule['ComparisonValue']) { "$($Rule['ComparisonValue'])" }
elseif ($null -ne $Rule['Value']) { "$($Rule['Value'])" }
else { $null }

switch ($kind) {
'File' {
$splat.Path = "$($Rule.Path)"
$splat.FileOrFolderName = "$($Rule.FileOrFolderName)"
$splat.FileOperation = if ($Rule.OperationType) { "$($Rule.OperationType)" }
else { "$($Rule.FileOperation)" }
$splat.Check32BitOn64System = [bool]$Rule.Check32BitOn64System
$splat.Path = "$($Rule['Path'])"
$splat.FileOrFolderName = "$($Rule['FileOrFolderName'])"
$splat.FileOperation = if ($Rule['OperationType']) { "$($Rule['OperationType'])" }
else { "$($Rule['FileOperation'])" }
$splat.Check32BitOn64System = [bool]$Rule['Check32BitOn64System']
}
'Registry' {
$splat.KeyPath = "$($Rule.KeyPath)"
if ($Rule.ValueName) { $splat.ValueName = "$($Rule.ValueName)" }
$splat.RegistryOperation = if ($Rule.OperationType) { "$($Rule.OperationType)" }
else { "$($Rule.RegistryOperation)" }
$splat.Check32BitOn64System = [bool]$Rule.Check32BitOn64System
$splat.KeyPath = "$($Rule['KeyPath'])"
if ($Rule['ValueName']) { $splat.ValueName = "$($Rule['ValueName'])" }
$splat.RegistryOperation = if ($Rule['OperationType']) { "$($Rule['OperationType'])" }
else { "$($Rule['RegistryOperation'])" }
$splat.Check32BitOn64System = [bool]$Rule['Check32BitOn64System']
}
'ProductCode' {
$splat.ProductCode = "$($Rule.ProductCode)"
if ($Rule.ProductVersionOperator -and "$($Rule.ProductVersionOperator)" -ne 'notConfigured') {
$operator = "$($Rule.ProductVersionOperator)"
$splat.ProductCode = "$($Rule['ProductCode'])"
if ($Rule['ProductVersionOperator'] -and "$($Rule['ProductVersionOperator'])" -ne 'notConfigured') {
$operator = "$($Rule['ProductVersionOperator'])"
}
if ($null -ne $Rule.ProductVersion) { $value = "$($Rule.ProductVersion)" }
if ($null -ne $Rule['ProductVersion']) { $value = "$($Rule['ProductVersion'])" }
}
'Script' { throw 'A PowerShell script rule is run with Invoke-IntuneDetectionTest, not evaluated here' }
default { throw "Rule needs a Type of File, Registry or ProductCode (or a win32LobApp*Rule @odata.type)" }
Expand Down
4 changes: 4 additions & 0 deletions Private/Get-IslAgentLogEvent.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,10 @@ function Get-IslAgentLogEvent {
}
}

# The event table, compiled by the first call of Get-IslAgentLogEvent. It is assigned here so
# that the test for it in the function reads a variable that exists, which strict mode requires.
$script:IslAgentLogEvents = $null

$script:IslAgentLogGuidRegex = [regex]::new(
'[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}',
[System.Text.RegularExpressions.RegexOptions]::Compiled)
Expand Down
15 changes: 10 additions & 5 deletions Private/Get-IslExportReport.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -46,22 +46,27 @@ function Get-IslExportReport {
if ($Select) { $body.select = $Select }
$jobs = '/beta/deviceManagement/reports/exportJobs'
$job = Invoke-IslGraphRequest -Uri $jobs -Method POST -Body $body
$jobStatus = "$(Get-IslPropertyValue -InputObject $job -Name 'status')"
$deadline = (Get-Date).AddSeconds($TimeoutSeconds)
while ("$($job.status)" -in 'notStarted', 'inProgress') {
while ($jobStatus -in 'notStarted', 'inProgress') {
if ((Get-Date) -gt $deadline) {
throw "The $ReportName export job did not complete within $TimeoutSeconds seconds"
}
Start-Sleep -Seconds 5
$job = Invoke-IslGraphRequest -Uri "$jobs/$($job.id)"
$jobId = Get-IslPropertyValue -InputObject $job -Name 'id'
$job = Invoke-IslGraphRequest -Uri "$jobs/$jobId"
$jobStatus = "$(Get-IslPropertyValue -InputObject $job -Name 'status')"
}
if ("$($job.status)" -ne 'completed' -or -not $job.url) {
throw "The $ReportName export job ended with status '$($job.status)'"
# The download address is there only once the job has completed
$jobUrl = Get-IslPropertyValue -InputObject $job -Name 'url'
if ($jobStatus -ne 'completed' -or -not $jobUrl) {
throw "The $ReportName export job ended with status '$jobStatus'"
}

$zipName = "IntuneScriptLab-$([guid]::NewGuid().ToString('N')).zip"
$zip = Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath $zipName
try {
Invoke-WebRequest -Uri $job.url -OutFile $zip -UseBasicParsing
Invoke-WebRequest -Uri $jobUrl -OutFile $zip -UseBasicParsing
Add-Type -AssemblyName System.IO.Compression.FileSystem
$archive = [System.IO.Compression.ZipFile]::OpenRead($zip)
try {
Expand Down
11 changes: 7 additions & 4 deletions Private/Get-IslLogonSession.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,19 @@ function Get-IslLogonSession {
$shells = @(Get-CimInstance -ClassName Win32_Process -Filter $filter -ErrorAction SilentlyContinue)
$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
$sid = (Invoke-CimMethod -InputObject $shell -MethodName GetOwnerSid -ErrorAction SilentlyContinue).Sid
if (-not $sid -or -not $owner.User) { continue }
$ownerSid = Invoke-CimMethod -InputObject $shell -MethodName GetOwnerSid -ErrorAction SilentlyContinue
$sid = Get-IslPropertyValue -InputObject $ownerSid -Name 'Sid'
$userName = Get-IslPropertyValue -InputObject $owner -Name 'User'
if (-not $sid -or -not $userName) { continue }
$key = "$($shell.SessionId)|$sid"
if ($seen.ContainsKey($key)) { continue }
$seen[$key] = $true
[pscustomobject]@{
PSTypeName = 'IntuneScriptLab.LogonSession'
UserName = $owner.User
Domain = $owner.Domain
UserName = $userName
Domain = Get-IslPropertyValue -InputObject $owner -Name 'Domain'
Sid = $sid
Id = [int]$shell.SessionId
}
Expand Down
67 changes: 67 additions & 0 deletions Private/Get-IslPropertyValue.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
function Get-IslPropertyValue {
<#
.SYNOPSIS
Gets a named value from a dictionary or an object, or nothing when it has none.

.DESCRIPTION
Data that reaches the module from outside has optional members and comes in two shapes: a
Graph reply is a dictionary or an object depending on how it was read, a rule or a settings
table is a hashtable the caller wrote, and a CIM call that fails returns nothing at all.
Under strict mode a read of a member that is not there is an error, so every such read goes
through this function, which returns nothing for a missing input, a missing key and a
missing property alike.

A collection is unrolled on the way out, like the output of any function. Wrap the call in
@() where the value is a list.

.PARAMETER InputObject
The dictionary or object to read from. Nothing is returned when it is $null.

.PARAMETER Name
The key or property name.

.EXAMPLE
Get-IslPropertyValue -InputObject $page -Name '@odata.nextLink'

The address of the next page of a Graph reply, or nothing on the last page.

.EXAMPLE
@(Get-IslPropertyValue -InputObject $policy -Name 'assignments')

The assignments of a policy as an array, empty when the reply has none.

.INPUTS
None.

.OUTPUTS
System.Object. The value, or nothing when the input has no such member.
#>
[CmdletBinding()]
[OutputType([object])]
param(
[Parameter()]
[AllowNull()]
[object]$InputObject,

[Parameter(Mandatory)]
[string]$Name
)

if ($null -eq $InputObject) {
return
}

if ($InputObject -is [System.Collections.IDictionary]) {
# Called through the interface: a generic dictionary implements this method explicitly,
# and PowerShell does not find it on the object itself
if (([System.Collections.IDictionary]$InputObject).Contains($Name)) {
return $InputObject[$Name]
}
return
}

$property = $InputObject.PSObject.Properties[$Name]
if ($null -ne $property) {
return $property.Value
}
}
23 changes: 15 additions & 8 deletions Private/Get-IslScriptContext.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -91,34 +91,41 @@ function Get-IslScriptContext {
'(?i)(^|[^a-z])(remediat\w*|fix)([^a-z]|$)' { 'Remediation'; break }
default { 'PlatformScript' }
}
# -Settings is optional, and a directive names only some of the four keys. An index reads a
# key the directive lacks as $null, and the accessor does the same for the settings object
$settingsType = Get-IslPropertyValue -InputObject $Settings -Name 'ScriptType'
$settingsContext = Get-IslPropertyValue -InputObject $Settings -Name 'Context'
$settingsArchitecture = Get-IslPropertyValue -InputObject $Settings -Name 'Architecture'
$settingsSignatureCheck = Get-IslPropertyValue -InputObject $Settings -Name 'EnforceSignatureCheck'

$typeSource = 'parameter'
if ($ScriptType -eq 'Auto') {
if ($directive.ScriptType) { $ScriptType = $directive.ScriptType; $typeSource = 'directive' }
elseif ($Settings.ScriptType) { $ScriptType = $Settings.ScriptType; $typeSource = 'settings' }
if ($directive['ScriptType']) { $ScriptType = $directive['ScriptType']; $typeSource = 'directive' }
elseif ($settingsType) { $ScriptType = $settingsType; $typeSource = 'settings' }
else { $ScriptType = $inferredType; $typeSource = $inferredSource }
}

# Intune's own defaults when nothing says otherwise. Portal defaults differ from API defaults
# (Findings.md, "Graph API defaults"); these are the portal ones because that is what most
# scripts get, and they are the more restrictive assumption for the rules.
if ($Context -eq 'Auto') {
$Context = if ($directive.Context) { $directive.Context }
elseif ($Settings.Context) { $Settings.Context }
$Context = if ($directive['Context']) { $directive['Context'] }
elseif ($settingsContext) { $settingsContext }
elseif ($ScriptType -eq 'PlatformScript') { 'User' } # portal default for platform scripts
else { 'System' }
}
if ($Architecture -eq 'Auto') {
$Architecture = if ($directive.Architecture) { $directive.Architecture }
elseif ($Settings.Architecture) { $Settings.Architecture }
$Architecture = if ($directive['Architecture']) { $directive['Architecture'] }
elseif ($settingsArchitecture) { $settingsArchitecture }
elseif ($ScriptType -in 'Win32Detection', 'Win32Requirement') { 'x64' } # 64-bit by default
else { 'x86' } # scripts/remediations: 32-bit
}

$signatureCheck = if ($EnforceSignatureCheck -ne 'Auto') { $EnforceSignatureCheck -eq 'True' }
elseif ($directive.ContainsKey('EnforceSignatureCheck')) {
"$($directive.EnforceSignatureCheck)" -in 'true', '1', 'yes'
"$($directive['EnforceSignatureCheck'])" -in 'true', '1', 'yes'
}
elseif ($null -ne $Settings.EnforceSignatureCheck) { [bool]$Settings.EnforceSignatureCheck }
elseif ($null -ne $settingsSignatureCheck) { [bool]$settingsSignatureCheck }
else { $false }

[pscustomobject]@{
Expand Down
Loading