Skip to content

Commit 36fcec3

Browse files
authored
Fix ForEach method to set property on a scalar object (PowerShell#17213)
1 parent c3b7e10 commit 36fcec3

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

src/System.Management.Automation/engine/runtime/Binding/Binders.cs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7454,7 +7454,20 @@ internal static object InvokeAdaptedMember(object obj, string methodName, object
74547454
if (string.Equals(methodName, "Foreach", StringComparison.OrdinalIgnoreCase))
74557455
{
74567456
var enumerator = (new object[] { obj }).GetEnumerator();
7457-
return EnumerableOps.ForEach(enumerator, args[0], Array.Empty<object>());
7457+
object[] argsToPass;
7458+
7459+
if (args.Length > 1)
7460+
{
7461+
int length = args.Length - 1;
7462+
argsToPass = new object[length];
7463+
Array.Copy(args, sourceIndex: 1, argsToPass, destinationIndex: 0, length: length);
7464+
}
7465+
else
7466+
{
7467+
argsToPass = Array.Empty<object>();
7468+
}
7469+
7470+
return EnumerableOps.ForEach(enumerator, args[0], argsToPass);
74587471
}
74597472

74607473
throw InterpreterError.NewInterpreterException(methodName, typeof(RuntimeException), null,

test/powershell/Language/Scripting/Scripting.Followup.Tests.ps1

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,10 @@ Describe "Scripting.Followup.Tests" -Tags "CI" {
3535
([bool]$var = 42).GetType().FullName | Should -Be "System.Boolean"
3636
. { ([bool]$var = 42).GetType().FullName } | Should -Be "System.Boolean"
3737
}
38+
39+
It "Setting property using 'ForEach' method should work on a scalar object" {
40+
$obj = [pscustomobject] @{ p = 1 }
41+
$obj.ForEach('p', 32) | Should -BeNullOrEmpty
42+
$obj.p | Should -Be 32
43+
}
3844
}

0 commit comments

Comments
 (0)