diff --git a/src/System.Management.Automation/engine/parser/Compiler.cs b/src/System.Management.Automation/engine/parser/Compiler.cs index 3426d326a9..3d8ec44487 100644 --- a/src/System.Management.Automation/engine/parser/Compiler.cs +++ b/src/System.Management.Automation/engine/parser/Compiler.cs @@ -4189,10 +4189,7 @@ namespace System.Management.Automation.Language // $foreach/$switch = GetEnumerator $enumerable var enumerable = NewTemp(typeof(object), "enumerable"); temps.Add(enumerable); - if (generatingForeach) - { - exprs.Add(UpdatePosition(stmt.Condition)); - } + exprs.Add(UpdatePosition(stmt.Condition)); exprs.Add( Expression.Assign(enumerable, GetRangeEnumerator(stmt.Condition.GetPureExpression()) diff --git a/test/powershell/Language/Scripting/ErrorPosition.Tests.ps1 b/test/powershell/Language/Scripting/ErrorPosition.Tests.ps1 new file mode 100644 index 0000000000..4012e7bd0f --- /dev/null +++ b/test/powershell/Language/Scripting/ErrorPosition.Tests.ps1 @@ -0,0 +1,51 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +Describe "Error position Tests" -Tags "CI" { + It "switch condition evaluation failure should report correct error position" { + $testFile = Join-Path $TestDrive "SwitchError1.ps1" + Set-Content -Path $testFile -Encoding Ascii -Value @' +$test = 1 +switch ($null[0]) { + "a" {}; +} +'@ + try { & $testFile } catch { $errorRecord = $_ } + $errorRecord | Should -Not -BeNullOrEmpty + $errorRecord.ScriptStackTrace | Should -Match "SwitchError1.ps1: line 2" + } + + It "switch condition MoveNext failure should report correct error position" { + $code = @' +using System; +using System.Collections.Generic; +namespace SwitchTest +{ + public class Test + { + public static IEnumerable GetName() + { + yield return "Hello world"; + throw new ArgumentException(); + } + } +} +'@ + $testFile = Join-Path $TestDrive "SwitchError2.ps1" + Set-Content -Path $testFile -Encoding Ascii -Value @' +$test = 1 +$enumerable = [SwitchTest.Test]::GetName() +switch ($enumerable) { + "hello world" { $test = 1; $_ } + "Yay" { $test = 2; $_ } +} +'@ + if (-not ("SwitchTest.Test" -as [type])) { + Add-Type -TypeDefinition $code + } + + try { & $testFile > $null } catch { $errorRecord = $_ } + $errorRecord | Should -Not -BeNullOrEmpty + $errorRecord.ScriptStackTrace | Should -Match "SwitchError2.ps1: line 3" + } +}