Script analyzer rules are often very simple; it is not always necessary for a rule to perform complex AST searches.
The following example evaluates the named blocks dynamicparam, begin, process, and end. If such a block is declared in a function, script, or script block, and it is empty, the rule will respond. The rule only accepts NamedBlockAst nodes; the script analyzer only passes matching nodes to the rule, and therefore, the rule itself does not have to worry about handling other node types:
using namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic
using namespace System.Management.Automation.Language
function PSAvoidEmptyNamedBlocks {
[CmdletBinding()]
[OutputType([Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.DiagnosticRecord])]
param (
[NamedBlockAst]$ast
)
if ($ast.Statements.Count -eq 0) {
[DiagnosticRecord]@{
Message = 'Empty {0} block.' -f $ast.BlockKind
Extent = $ast.Extent
RuleName = $myinvocation.MyCommand.Name
Severity = 'Warning'
}
}
}
The rule returns DiagnosticRecord when it is triggered. The record is returned by the script analyzer as long as the rule is not suppressed.