@@ -98,6 +98,19 @@ public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
98
98
// find all declared parameters
99
99
IEnumerable < Ast > parameterAsts = scriptBlockAst . FindAll ( oneAst => oneAst is ParameterAst , false ) ;
100
100
101
+ // does the scriptblock have a process block where either $PSItem or $_ is referenced
102
+ bool hasProcessBlockWithPSItemOrUnderscore = false ;
103
+ if ( scriptBlockAst . ProcessBlock != null )
104
+ {
105
+ IDictionary < string , int > processBlockVariableCount = GetVariableCount ( scriptBlockAst . ProcessBlock ) ;
106
+ processBlockVariableCount . TryGetValue ( "_" , out int underscoreVariableCount ) ;
107
+ processBlockVariableCount . TryGetValue ( "psitem" , out int psitemVariableCount ) ;
108
+ if ( underscoreVariableCount > 0 || psitemVariableCount > 0 )
109
+ {
110
+ hasProcessBlockWithPSItemOrUnderscore = true ;
111
+ }
112
+ }
113
+
101
114
// list all variables
102
115
IDictionary < string , int > variableCount = GetVariableCount ( scriptBlockAst ) ;
103
116
@@ -108,18 +121,14 @@ public IEnumerable<DiagnosticRecord> AnalyzeScript(Ast ast, string fileName)
108
121
valFromPipelineAst => valFromPipelineAst is NamedAttributeArgumentAst namedAttrib && string . Equals (
109
122
namedAttrib . ArgumentName , "ValueFromPipeline" ,
110
123
StringComparison . OrdinalIgnoreCase
111
- ) ,
124
+ ) ,
112
125
false
113
126
) ;
114
- // If the parameter has the ValueFromPipeline attribute, check for usages of $_ or $PSItem
115
- if ( valueFromPipeline ? . GetValue ( ) == true )
127
+ // If the parameter has the ValueFromPipeline attribute and the scriptblock has a process block with
128
+ // $_ or $PSItem usage, then the parameter is considered used
129
+ if ( valueFromPipeline ? . GetValue ( ) == true && hasProcessBlockWithPSItemOrUnderscore )
116
130
{
117
- variableCount . TryGetValue ( "_" , out int underscoreVariableCount ) ;
118
- variableCount . TryGetValue ( "psitem" , out int psitemVariableCount ) ;
119
- if ( underscoreVariableCount > 0 || psitemVariableCount > 0 )
120
- {
121
- continue ;
122
- }
131
+ continue ;
123
132
}
124
133
125
134
// there should be at least two usages of the variable since the parameter declaration counts as one
@@ -240,7 +249,7 @@ public string GetSourceName()
240
249
/// <param name="ast">The scriptblock ast to scan</param>
241
250
/// <param name="data">Previously generated data. New findings are added to any existing dictionary if present</param>
242
251
/// <returns>a dictionary including all variables in the scriptblock and their count</returns>
243
- IDictionary < string , int > GetVariableCount ( ScriptBlockAst ast , Dictionary < string , int > data = null )
252
+ IDictionary < string , int > GetVariableCount ( Ast ast , Dictionary < string , int > data = null )
244
253
{
245
254
Dictionary < string , int > content = data ;
246
255
if ( null == data )
0 commit comments