PSScriptAnalyzer deep dive – Part 4 of 4


Summary: Thomas Rayner, Microsoft Cloud and Datacenter Management MVP, shows how to write a custom PSScriptAnalyzer rule.

Hello! I’m Thomas Rayner, a Cloud and Datacenter Management Microsoft MVP, filling in for The Scripting Guy this week. You can find me on Twitter (@MrThomasRayner), or posting on my blog, workingsysadmin.com. This week, I’m presenting a four-part series about how to use PSScriptAnalyzer.

Part 1 – Getting started with PSScriptAnalyzer

Part 2 – Suppressing, including, excluding rules

Part 3 – Wrapping PSScriptAnalyzer with Pester to get formatted results

Part 4 – Writing custom rules

This is Part 4, so let’s look at how to write your own custom PSScriptAnalyzer rules.

At this time, PSScriptAnalyzer comes with a total of 45 rules that are based on community best practices. PowerShell team members at Microsoft and the community developed these rules. The built-in rules are a great baseline, and a good starting point that will quickly tell you if a script or module has any glaring flaws before you get too deep into it. That’s great, but what if you or your team has some more stringent standards, or you want to borrow the PSSA engine to check scripts for some other reason? You’ll need a custom rule.

Before we go further, here’s the script that I’m going to be testing today, saved as MyScript.ps1. It’s pretty useless because I’m just trying to highlight some PSSA functionality.

function Get-Something {

param (
[string]$Words

)

Write-Host "You said $Words"

}

function Get-MYVar {

param (
[string]$VariableName

)

$results = $null

Get-Variable -Name $VariableName

}

Like with most of my other pieces of example code in this series, and especially if you’ve been following the rest of this series, you should already see some things that are going to trigger some PSSA rule violations.

Result of running MyScript.ps1 to trigger PSSA rule violations

I’m declaring a variable that I never actually use, and I’m using Write-Host. Both actions are violations of standard PSSA rules.

Maybe there are more issues with my script, though. Perhaps in my organization, it is against my style and standards guidelines to have a function that has adjacent capital letters. Instead of having Get-MYVar, I should have Get-MyVar. Plenty of people support this rule because it increases readability. Instead of something like Get-AzureRMVM, you can have Get-AzureRmVm, which is more readable.

PSSA didn’t tell me about my function whose name has adjacent capital letters, though. I know that I can use the regex pattern ‘[A-Z]{2,}’ to detect two capital letters in a row, but how do I write a PSSA rule?

To write custom PSScriptAnalyzer rules, you’ll need at least basic knowledge of the PowerShell abstract syntax tree. The PowerShell abstract syntax tree is a tree-style representation of the code that makes up whatever you’ve written. Tools that are built into .NET and PowerShell parse files for examination by tools like, but not limited to, PSSA. Doing a deep dive on the abstract syntax tree could be its own five-part series. If that’s something you’d like to see, contact me by using my information at the beginning of this post. If the demand is there, I will put one together. For now, I’m just going to recommend that you do a little independent learning if what you see in this post is too far over your head. The abstract syntax tree is a bit of an abstract concept (pun intended) to get into, but a few really good blog posts and info pages are out there already.

So, let’s get into it. PSSA custom rules are just PowerShell functions. I’m going to make a new file named MyRule.psm1 and start to build my function. Note that the file needs to be a .psm1. Otherwise, it won’t work properly.

function Test-FunctionCasing {

[CmdletBinding()]
[OutputType([PSCustomObject[]])]
param (

[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.Language.ScriptBlockAst]$ScriptBlockAst

)

}

My custom rule is going to be named Test-FunctionCasing. Custom PSSA rules output PSCustomObject objects and take some form of abstract syntax tree object as input. For this scenario, I want to use the ScriptBlockAst objects in my script because that’s the part of the tree that will give me what I need to check function names.

Note: I’ve started a module, called AstHelper, that’s geared towards helping people discover and use the abstract syntax tree. It’s available on the PowerShell Gallery (Find-Module AstHelper), and if you’d like to contribute, the source is on GitHub (https://github.com/ThmsRynr/AstHelper). At this time, it’s very much in it’s infancy, but I still use it to discover what types of abstract syntax tree objects are in PowerShell scripts and modules, and what kind of objects are in there that are of “AST type ___”. Jason Shirk also built a cool module for exploring abstract syntax tree (https://github.com/lzybkr/ShowPSAst).

Back to our custom rule. I’m going to add a process block next.

process {

try {

$functions = $ScriptBlockAst.FindAll( { $args[0] -is [System.Management.Automation.Language.FunctionDefinitionAst] -and

$args[0].Name -cmatch '[A-Z]{2,}' }, $true )

}

catch {

$PSCmdlet.ThrowTerminatingError( $_ )

}

}

Here, I’m getting all the functions that have a name that matches my regex pattern of “two adjacent capital letters”. I’ve wrapped this in a try / catch, just in case. The .FindAll() syntax is somewhat robust, and it can be daunting if you are not familiar with it. Microsoft has it well documented at Ast.FindAll Method (Func<Ast, Boolean>, Boolean).

Now, I just need a foreach loop to go through all the functions that matched the pattern and report them to PSSA.

foreach ( $function in $functions ) {

[PSCustomObject]@{

Message  = "Avoid function names with adjacent caps in their name"
Extent   = $function.Extent
RuleName = $PSCmdlet.MyInvocation.InvocationName
Severity = "Warning"
}

}

All I need to do is specify a message, an extent (built in to the result stored in $function), the rule name that it violated (which is the name of the PowerShell function I’m building), and severity.

My entire, assembled rule looks like this.

function Test-FunctionCasing {

[CmdletBinding()]
[OutputType([PSCustomObject[]])]
param (

[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.Language.ScriptBlockAst]$ScriptBlockAst

)

process {

try {

$functions = $ScriptBlockAst.FindAll( { $args[0] -is [System.Management.Automation.Language.FunctionDefinitionAst] -and

$args[0].Name -cmatch '[A-Z]{2,}' }, $true )
foreach ( $function in $functions ) {
[PSCustomObject]@{
Message  = "Avoid function names with adjacent caps in their name"
Extent   = $function.Extent
RuleName = $PSCmdlet.MyInvocation.InvocationName
Severity = "Warning"
}

}

}

catch {

$PSCmdlet.ThrowTerminatingError( $_ )

}

}

}

Now, I save MyRule.psm1, and I can include it when I run Invoke-ScriptAnalyzer.

Invoke-ScriptAnalyzer -Path .\MyScript.ps1 -CustomRulePath .\MyRule.psm1

And I get back a violation that looks just like you’d think it should.

Example of a violation

But wait. Doesn’t MyScript.ps1 violate some of the standard rules too? Where are those violations?

Well, if we want to include the standard rules when we’re using custom rules, we just need to add one parameter to our Invoke-ScriptAnalyzer command.

Invoke-ScriptAnalyzer -Path .\MyScript.ps1 -CustomRulePath .\MyRule.psm1 -IncludeDefaultRules

That looks better!

3-hsg-020317

That’s it! This concludes my four-part deep dive on PSScriptAnalyzer. Hopefully, you’ve learned something about PSSA and have seen that even though this was a deep dive, the rabbit hole goes much deeper.

Happy scripting!

Thomas! That was a great set, and now you’ve got my brain churning! I’ll be sure to have my PC wrapped this weekend playing with all these cool new ideas! Thanks!

I invite you to follow the Scripting Guys on Twitter and Facebook. If you have any questions, send email to them at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow.

Until then, always remember that with Great PowerShell comes Great Responsibility.

Sean Kearney
Honorary Scripting Guy
Cloud and Datacenter Management MVP

Comments (0)

Skip to main content