Skip to content

Commit 77798ba

Browse files
nohwndCopilot
andauthored
Fix #2585: Prevent $WhatIfPreference from breaking Pester (#2730)
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>
1 parent d42d374 commit 77798ba

2 files changed

Lines changed: 30 additions & 0 deletions

File tree

src/Main.ps1

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -454,6 +454,10 @@ function Invoke-Pester {
454454
[PesterConfiguration] $Configuration
455455
)
456456
begin {
457+
# Prevent $WhatIfPreference from leaking into Pester internals (#2585).
458+
# When the caller sets $WhatIfPreference = $true, it propagates to child
459+
# scopes and breaks commands that Pester relies on (New-Item, Remove-Item, etc.).
460+
$WhatIfPreference = $false
457461
$start = [DateTime]::Now
458462
# this will inherit to child scopes and allow Describe / Context to run directly from a file or command line
459463
$invokedViaInvokePester = $true

tst/Pester.RSpec.InNewProcess.ts.ps1

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -391,4 +391,30 @@ i -PassThru:$PassThru {
391391
}
392392
}
393393
}
394+
395+
b '$WhatIfPreference does not break Pester' {
396+
t 'Invoke-Pester succeeds when $WhatIfPreference is $true' {
397+
$sb = {
398+
$WhatIfPreference = $true
399+
400+
$PesterPreference = [PesterConfiguration]::Default
401+
$PesterPreference.Output.Verbosity = 'None'
402+
403+
$container = New-PesterContainer -ScriptBlock {
404+
Describe 'd1' {
405+
It 'i1' {
406+
1 | Should -Be 1
407+
}
408+
}
409+
}
410+
$r = Invoke-Pester -Container $container -PassThru
411+
if ($r.FailedCount -ne 0) { throw "Expected 0 failures, got $($r.FailedCount)" }
412+
if ($r.PassedCount -ne 1) { throw "Expected 1 passed, got $($r.PassedCount)" }
413+
}
414+
415+
$output = Invoke-InNewProcess $sb
416+
$whatIfLines = $output | Select-String -Pattern 'What if:'
417+
@($whatIfLines).Count | Verify-Equal 0
418+
}
419+
}
394420
}

0 commit comments

Comments
 (0)