From 33d108cdfa15bde714ee664b6239a6a29dc0da5c Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Fri, 24 Jul 2026 12:47:04 -0700 Subject: [PATCH] Fix the dot-sourcing behavior of `pwsh -file` for advanced-function scripts (#27727) --- src/System.Management.Automation/engine/CommandProcessor.cs | 4 +++- .../engine/runtime/CompiledScriptBlock.cs | 2 ++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/CommandProcessor.cs b/src/System.Management.Automation/engine/CommandProcessor.cs index d9758cea2fa..4c176bb21d1 100644 --- a/src/System.Management.Automation/engine/CommandProcessor.cs +++ b/src/System.Management.Automation/engine/CommandProcessor.cs @@ -778,7 +778,9 @@ private void Init(IScriptCommandInfo scriptCommandInfo) InitCommon(); // If the script has been dotted, throw an error if it's from a different language mode. - if (!this.UseLocalScope) + // Unless it was a script loaded through -File, in which case the danger of dotting other + // language modes (getting internal functions in the user's state) isn't a danger. + if (!this.UseLocalScope && !scriptCmdlet.ShouldRethrowExitException) { ValidateCompatibleLanguageMode(scriptCommandInfo.ScriptBlock, _context, Command.MyInvocation); } diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index 2569dd3a492..651303375fd 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -2191,6 +2191,8 @@ internal sealed class PSScriptCmdlet : PSCmdlet, IDynamicParameters, IDisposable private bool _exitWasCalled; private bool _anyClauseExecuted; + internal bool ShouldRethrowExitException => _rethrowExitException; + public PSScriptCmdlet(ScriptBlock scriptBlock, bool useNewScope, bool fromScriptFile, ExecutionContext context) { _scriptBlock = scriptBlock;