@@ -5375,6 +5375,20 @@ private static void AddUniqueVariable(HashSet<string> hashedResults, List<Comple
5375
5375
"pv"
5376
5376
} ;
5377
5377
5378
+ private static readonly HashSet < string > s_localScopeCommandNames = new ( StringComparer . OrdinalIgnoreCase )
5379
+ {
5380
+ "Microsoft.PowerShell.Core\\ ForEach-Object" ,
5381
+ "ForEach-Object" ,
5382
+ "foreach" ,
5383
+ "%" ,
5384
+ "Microsoft.PowerShell.Core\\ Where-Object" ,
5385
+ "Where-Object" ,
5386
+ "where" ,
5387
+ "?" ,
5388
+ "BeforeAll" ,
5389
+ "BeforeEach"
5390
+ } ;
5391
+
5378
5392
private sealed class VariableInfo
5379
5393
{
5380
5394
internal Type LastDeclaredConstraint ;
@@ -5616,12 +5630,31 @@ public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst fun
5616
5630
5617
5631
public override AstVisitAction VisitScriptBlockExpression ( ScriptBlockExpressionAst scriptBlockExpressionAst )
5618
5632
{
5619
- return scriptBlockExpressionAst != Top ? AstVisitAction . SkipChildren : AstVisitAction . Continue ;
5620
- }
5633
+ if ( scriptBlockExpressionAst == Top )
5634
+ {
5635
+ return AstVisitAction . Continue ;
5636
+ }
5621
5637
5622
- public override AstVisitAction VisitScriptBlock ( ScriptBlockAst scriptBlockAst )
5623
- {
5624
- return scriptBlockAst != Top ? AstVisitAction . SkipChildren : AstVisitAction . Continue ;
5638
+ Ast parent = scriptBlockExpressionAst . Parent ;
5639
+ // This loop checks if the scriptblock is used as a command, or an argument for a command, eg: ForEach-Object -Process {$Var1 = "Hello"}, {Var2 = $true}
5640
+ while ( true )
5641
+ {
5642
+ if ( parent is CommandAst cmdAst )
5643
+ {
5644
+ string cmdName = cmdAst . GetCommandName ( ) ;
5645
+ return s_localScopeCommandNames . Contains ( cmdName )
5646
+ || ( cmdAst . CommandElements [ 0 ] is ScriptBlockExpressionAst && cmdAst . InvocationOperator == TokenKind . Dot )
5647
+ ? AstVisitAction . Continue
5648
+ : AstVisitAction . SkipChildren ;
5649
+ }
5650
+
5651
+ if ( parent is not CommandExpressionAst and not PipelineAst and not StatementBlockAst and not ArrayExpressionAst and not ArrayLiteralAst )
5652
+ {
5653
+ return AstVisitAction . SkipChildren ;
5654
+ }
5655
+
5656
+ parent = parent . Parent ;
5657
+ }
5625
5658
}
5626
5659
}
5627
5660
0 commit comments