-
Notifications
You must be signed in to change notification settings - Fork 397
Description
Summary of the new feature
This idea came from a sidebar comment from @thomasrayner in #1308. The UseDeclaredVarsMoreThanAssignments
rule currently warns for variables that are declared but never used. If this is a valuable rule then it follows that we would want to check for parameters that are declared and never used.
Essentially I'd like to see if anyone else considers this valuable based on the proposed initial implementation below, or if you can think of edge cases or roadblocks I might not have thought of.
Proposed technical implementation details (optional)
I have a POC rule that is working at a basic level:
// find all declared parameters
IEnumerable<Ast> parameterAsts = ast.FindAll(a => a is ParameterAst, true);
// list all variables
List<string> variables = ast.FindAll(a => a is VariableExpressionAst, true)
.Cast<VariableExpressionAst>()
.Select(v => v.VariablePath.ToString())
.ToList();
foreach (ParameterAst parameterAst in parameterAsts)
{
// compare the list of variables to the parameter name
// there should be at least two matches of the variable name since the parameter declaration counts as one
int matchCount = variables
.Where(x => x == parameterAst.Name.VariablePath.ToString())
.Count();
if (matchCount > 1)
{
continue;
}
// all bets are off if the script uses PSBoundParameters
if (variables.Contains("PSBoundParameters"))
{
continue;
}
yield return new DiagnosticRecord...
}
I think this approach could work but there are definitely some tricky usages to work around:
-
a parameter could be used explicitly or splatted using
$PSBoundParameters
or$PSCmdlet.MyInvocation.BoundParameters
. One way around this is to simply check if either of those are used in the scripblock, but this isn't a guarantee as the bound parameters collection could be modified prior to its use. Of course, we could also check that theRemove()
method has not been called on either of these collections. -
We'd need to check for the use of
Get-Variable
as well.
I'm sure there are other cases I'm not aware of but will discover in testing.
What is the latest version of PSScriptAnalyzer at the point of writing
1.8.3