From c2e75b3cffaaaa63e5db9b7a11d4fa4858779780 Mon Sep 17 00:00:00 2001 From: Jakub Jares Date: Wed, 17 Jun 2026 15:47:01 +0200 Subject: [PATCH] Fix #2585: Prevent $WhatIfPreference from breaking Pester Set $WhatIfPreference = $false at the start of Invoke-Pester's begin block. When a caller sets $WhatIfPreference = $true, it leaks into Pester's internal commands (New-Item, Remove-Item, etc.) and causes test execution to fail with cryptic errors or excessive 'What if:' messages. The local assignment scopes it to Invoke-Pester and its children without affecting the caller's preference. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/Main.ps1 | 4 ++++ tst/Pester.RSpec.InNewProcess.ts.ps1 | 26 ++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/src/Main.ps1 b/src/Main.ps1 index 4430e6ed6..0ff407707 100644 --- a/src/Main.ps1 +++ b/src/Main.ps1 @@ -454,6 +454,10 @@ function Invoke-Pester { [PesterConfiguration] $Configuration ) begin { + # Prevent $WhatIfPreference from leaking into Pester internals (#2585). + # When the caller sets $WhatIfPreference = $true, it propagates to child + # scopes and breaks commands that Pester relies on (New-Item, Remove-Item, etc.). + $WhatIfPreference = $false $start = [DateTime]::Now # this will inherit to child scopes and allow Describe / Context to run directly from a file or command line $invokedViaInvokePester = $true diff --git a/tst/Pester.RSpec.InNewProcess.ts.ps1 b/tst/Pester.RSpec.InNewProcess.ts.ps1 index a1e869d9e..b66329305 100644 --- a/tst/Pester.RSpec.InNewProcess.ts.ps1 +++ b/tst/Pester.RSpec.InNewProcess.ts.ps1 @@ -391,4 +391,30 @@ i -PassThru:$PassThru { } } } + + b '$WhatIfPreference does not break Pester' { + t 'Invoke-Pester succeeds when $WhatIfPreference is $true' { + $sb = { + $WhatIfPreference = $true + + $PesterPreference = [PesterConfiguration]::Default + $PesterPreference.Output.Verbosity = 'None' + + $container = New-PesterContainer -ScriptBlock { + Describe 'd1' { + It 'i1' { + 1 | Should -Be 1 + } + } + } + $r = Invoke-Pester -Container $container -PassThru + if ($r.FailedCount -ne 0) { throw "Expected 0 failures, got $($r.FailedCount)" } + if ($r.PassedCount -ne 1) { throw "Expected 1 passed, got $($r.PassedCount)" } + } + + $output = Invoke-InNewProcess $sb + $whatIfLines = $output | Select-String -Pattern 'What if:' + @($whatIfLines).Count | Verify-Equal 0 + } + } }