diff --git a/src/functions/TestResults.ps1 b/src/functions/TestResults.ps1 index dd3404d0d..42b3d041a 100644 --- a/src/functions/TestResults.ps1 +++ b/src/functions/TestResults.ps1 @@ -468,10 +468,10 @@ function Get-RunTimeEnvironment { $computerName = $env:ComputerName $userName = $env:Username if ($null -ne $SafeCommands['Get-CimInstance']) { - $osSystemInformation = (& $SafeCommands['Get-CimInstance'] Win32_OperatingSystem) + $osSystemInformation = (& $SafeCommands['Get-CimInstance'] Win32_OperatingSystem -ErrorAction Ignore) } elseif ($null -ne $SafeCommands['Get-WmiObject']) { - $osSystemInformation = (& $SafeCommands['Get-WmiObject'] Win32_OperatingSystem) + $osSystemInformation = (& $SafeCommands['Get-WmiObject'] Win32_OperatingSystem -ErrorAction Ignore) } elseif ($IsMacOS -or $IsLinux) { $osSystemInformation = @{ @@ -492,7 +492,9 @@ function Get-RunTimeEnvironment { # well, we tried } } - else { + + # Fall back to unknown values if WMI/CIM returned null (e.g. access denied when not running as Administrator) + if ($null -eq $osSystemInformation) { $osSystemInformation = @{ Name = 'Unknown' Version = '0.0.0.0' diff --git a/tst/functions/TestResults.Tests.ps1 b/tst/functions/TestResults.Tests.ps1 index e8442df3b..07bffe474 100644 --- a/tst/functions/TestResults.Tests.ps1 +++ b/tst/functions/TestResults.Tests.ps1 @@ -91,4 +91,28 @@ InPesterModuleScope { Pop-Location } + + # Regression test for https://github.com/pester/Pester/issues/2678 + # Get-CimInstance can fail with access denied when not running as Administrator. + # The fix adds -ErrorAction Ignore and a fallback to prevent the entire test report + # from failing just because OS info is unavailable. + Describe "Get-RunTimeEnvironment" { + It "Returns a hashtable with expected keys without throwing" { + $result = Get-RunTimeEnvironment + $result | Should -BeOfType [hashtable] + $result.Keys | Should -Contain 'os-version' + $result.Keys | Should -Contain 'platform' + $result.Keys | Should -Contain 'machine-name' + $result.Keys | Should -Contain 'user' + $result.Keys | Should -Contain 'cwd' + $result.Keys | Should -Contain 'clr-version' + } + + It "Returns non-null os-version and platform values" { + # Even with access denied, the fallback should provide 'Unknown' / '0.0.0.0' + $result = Get-RunTimeEnvironment + $result['os-version'] | Should -Not -BeNullOrEmpty + $result['platform'] | Should -Not -BeNullOrEmpty + } + } }