PowerShell / PSScriptAnalyzer

Download ScriptAnalyzer from PowerShellGallery
https://www.powershellgallery.com/packages/PSScriptAnalyzer/
MIT License
1.87k stars 379 forks source link

Rule request: PossibleArgumentWithOperatorConfusion #2014

Open iRon7 opened 4 months ago

iRon7 commented 4 months ago

PowerShell has two parsing modes:

It is not always clear whenever PowerShell is in argument mode, as in:

if (&{ (1,2,3).Where{ $_ -eq 4 } } -isnot [int]) { Throw "The expression should return an integer"

For background information, see: Call operator (&{}) with no results doesn't type compare #24054

Yet from the argument name (and position and the operators) you could make a reasonable assumption that it probably concerns an operator instead.

For a (PowerShell based) rule prototype, see: https://github.com/iRon7/PSRules/blob/main/PossibleArgumentWithOperatorConfusion.psm1

Invoke-ScriptAnalyzer -CustomRulePath $RulePath -ScriptDefinition 'if (&{ (1,2,3).Where{ $_ -eq 4 } } -isnot [int]) { Throw "The expression should return an integer" }' | Select-Object *

Line                 : 1
Column               : 5
Message              : Possible argument with operator (-isnot) confusion.
Extent               : &{ (1,2,3).Where{ $_ -eq 4 } } -isnot [int]
RuleName             : PSPossibleArgumentWithOperatorConfusion
Severity             : Warning
ScriptName           :
ScriptPath           :
RuleSuppressionID    :
SuggestedCorrections : {(&{ (1,2,3).Where{ $_ -eq 4} }) -isnot [int]}
IsSuppressed         : False
iRon7 commented 4 months ago

I did a number of improvements to my prototype but in fact the scope of the rule could be even more wider and might also applied to (incorrect) statements like:

Get-Date - $StartTime

Get-Date: Cannot bind parameter 'Date'. Cannot convert value "-" to type "System.DateTime". Error: "String '-' was not recognized as a valid DateTime."

Although it would already generate a clear error during run time, it would be nice to get the message and suggested correction during design time:

(Get-Date) - $StartTime

Related: #24079 Add $Now to the automatic variables