PSScriptAnalyzer icon indicating copy to clipboard operation
PSScriptAnalyzer copied to clipboard

Rule request: The Catch (or Finally) statement is missing its Try block.

Open iRon7 opened this issue 10 months ago • 3 comments

There is a rule for The Try statement is missing its Catch or Finally block.:

Invoke-ScriptAnalyzer -ScriptDefinition {function Test { Try { write-verbose 'Test' } }}.ToString()
ParserError:
Line |
   1 |  … criptDefinition {function Test { Try { write-verbose 'Test' } }}.ToSt …
     |                                                                 ~
     | The Try statement is missing its Catch or Finally block.

But there is no rule for the opposite: a Catch (or Finally) statement that is missing its Try block:

Invoke-ScriptAnalyzer -ScriptDefinition {function Test { Catch { write-verbose 'Test' } }}.ToString()

Even it produces a syntax error during run time (as it assumes it is a cmdlet, which is definitely not a recommend function name):

Catch { write-verbose'Test' }
Catch: The term 'Catch' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

iRon7 avatar Apr 29 '25 12:04 iRon7

If you look at the first output, there is no rule, PSSA just passes the parser error back. PSSA generally relies on parser and if parser cannot tell whether this is a command or catch block with no try block, then life will be hard because there must be a reason, which is likely PowerShell's generic nature that one could write a function called catch that accepts a scriptblock

bergmeister avatar Apr 29 '25 20:04 bergmeister

If you look at the first output, there is no rule, PSSA just passes the parser error back.

Right, I missed that.

there must be a reason, which is likely PowerShell's generic nature that one could write a function called catch that accepts a scriptblock

Apart from the fact that this probably concerns a mistake (that actually happend in our environment), it concerns a reserved word which cannot be used as identifiers because they have a special meaning in PowerShell. I did an additional rule request for this, see: https://github.com/PowerShell/PSScriptAnalyzer/issues/2099

iRon7 avatar Apr 30 '25 07:04 iRon7

@bergmeister, Taken the response from the Engine WG: https://github.com/PowerShell/PowerShell/issues/25491#issuecomment-2851915260, I still think this is a valid rule request for the script analyzer.

iRon7 avatar May 12 '25 12:05 iRon7