Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
iRon7 opened this issue Apr 29, 2025 · 3 comments
Open

Comments

@iRon7
Copy link

iRon7 commented Apr 29, 2025

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.
@bergmeister
Copy link
Collaborator

bergmeister commented Apr 29, 2025

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

@iRon7
Copy link
Author

iRon7 commented Apr 30, 2025

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: #2099

@iRon7
Copy link
Author

iRon7 commented May 12, 2025

@bergmeister,
Taken the response from the Engine WG: PowerShell/PowerShell#25491 (comment),
I still think this is a valid rule request for the script analyzer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants