Skip to content

Commit 5d6abc8

Browse files
nohwndCopilot
andcommitted
Fix #2678: Suppress Get-CimInstance access denied error
Copilot-generated fix. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent d5f7c87 commit 5d6abc8

2 files changed

Lines changed: 29 additions & 3 deletions

File tree

src/functions/TestResults.ps1

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -468,10 +468,10 @@ function Get-RunTimeEnvironment {
468468
$computerName = $env:ComputerName
469469
$userName = $env:Username
470470
if ($null -ne $SafeCommands['Get-CimInstance']) {
471-
$osSystemInformation = (& $SafeCommands['Get-CimInstance'] Win32_OperatingSystem)
471+
$osSystemInformation = (& $SafeCommands['Get-CimInstance'] Win32_OperatingSystem -ErrorAction Ignore)
472472
}
473473
elseif ($null -ne $SafeCommands['Get-WmiObject']) {
474-
$osSystemInformation = (& $SafeCommands['Get-WmiObject'] Win32_OperatingSystem)
474+
$osSystemInformation = (& $SafeCommands['Get-WmiObject'] Win32_OperatingSystem -ErrorAction Ignore)
475475
}
476476
elseif ($IsMacOS -or $IsLinux) {
477477
$osSystemInformation = @{
@@ -492,7 +492,9 @@ function Get-RunTimeEnvironment {
492492
# well, we tried
493493
}
494494
}
495-
else {
495+
496+
# Fall back to unknown values if WMI/CIM returned null (e.g. access denied when not running as Administrator)
497+
if ($null -eq $osSystemInformation) {
496498
$osSystemInformation = @{
497499
Name = 'Unknown'
498500
Version = '0.0.0.0'

tst/functions/TestResults.Tests.ps1

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,4 +91,28 @@ InPesterModuleScope {
9191
Pop-Location
9292

9393
}
94+
95+
# Regression test for https://github.com/pester/Pester/issues/2678
96+
# Get-CimInstance can fail with access denied when not running as Administrator.
97+
# The fix adds -ErrorAction Ignore and a fallback to prevent the entire test report
98+
# from failing just because OS info is unavailable.
99+
Describe "Get-RunTimeEnvironment" {
100+
It "Returns a hashtable with expected keys without throwing" {
101+
$result = Get-RunTimeEnvironment
102+
$result | Should -BeOfType [hashtable]
103+
$result.Keys | Should -Contain 'os-version'
104+
$result.Keys | Should -Contain 'platform'
105+
$result.Keys | Should -Contain 'machine-name'
106+
$result.Keys | Should -Contain 'user'
107+
$result.Keys | Should -Contain 'cwd'
108+
$result.Keys | Should -Contain 'clr-version'
109+
}
110+
111+
It "Returns non-null os-version and platform values" {
112+
# Even with access denied, the fallback should provide 'Unknown' / '0.0.0.0'
113+
$result = Get-RunTimeEnvironment
114+
$result['os-version'] | Should -Not -BeNullOrEmpty
115+
$result['platform'] | Should -Not -BeNullOrEmpty
116+
}
117+
}
94118
}

0 commit comments

Comments
 (0)