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 + } + } }