From 506869c157fbd481a3f6f9f9e50d9d0efec1fede Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Mon, 22 Sep 2025 21:19:39 -0700 Subject: [PATCH] Fix `-Debug` to not trigger the `ShouldProcess` prompt (#26081) --- .../engine/MshCommandRuntime.cs | 12 +++--- .../Write-Debug.Tests.ps1 | 40 +++++++++++++++++++ 2 files changed, 45 insertions(+), 7 deletions(-) diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index 883c800dea..2e5cdb455b 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -2992,21 +2992,19 @@ namespace System.Management.Automation { // WhatIf not relevant, it never gets this far in that case if (Confirm) - return ConfirmImpact.Low; - if (Debug) { - if (IsConfirmFlagSet) // -Debug -Confirm:$false - return ConfirmImpact.None; return ConfirmImpact.Low; } - if (IsConfirmFlagSet) // -Confirm:$false + if (IsConfirmFlagSet) + { + // -Confirm:$false return ConfirmImpact.None; + } if (!_isConfirmPreferenceCached) { - bool defaultUsed = false; - _confirmPreference = Context.GetEnumPreference(SpecialVariables.ConfirmPreferenceVarPath, _confirmPreference, out defaultUsed); + _confirmPreference = Context.GetEnumPreference(SpecialVariables.ConfirmPreferenceVarPath, _confirmPreference, out _); _isConfirmPreferenceCached = true; } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Debug.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Debug.Tests.ps1 index f93027cc57..951400349c 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Debug.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Write-Debug.Tests.ps1 @@ -34,4 +34,44 @@ Describe "Write-Debug tests" -Tags "CI" { $out = $p.StandardError.ReadToEnd() $out | Should -BeNullOrEmpty } + + It "'-Debug' should not trigger 'ShouldProcess'" { + $pwsh = [PowerShell]::Create() + $pwsh.AddScript(@' +function Test-DebugWithConfirm +{ + [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Low')] + Param () + + PROCESS + { + Write-Debug -Message "Debug_Message1" + If ($PSCmdlet.ShouldProcess('Doing the thing.','Proceed?','Ready to do the thing.')) + { + Write-Output 'success' + } + Write-Debug -Message "Debug_Message2" + } + + END {} +} +'@) + $pwsh.Invoke() + $pwsh.Commands.Clear() + $pwsh.Streams.ClearStreams() + + try { + $result = $pwsh.AddScript("Test-DebugWithConfirm -Debug").Invoke() + $result.Count | Should -BeExactly 1 + $result[0] | Should -BeExactly 'success' + + $pwsh.Streams.Error.Count | Should -BeExactly 0 + $pwsh.Streams.Debug.Count | Should -BeExactly 2 + $pwsh.Streams.Debug[0] | Should -BeExactly 'Debug_Message1' + $pwsh.Streams.Debug[1] | Should -BeExactly 'Debug_Message2' + } + finally { + $pwsh.Dispose() + } + } }