While developing scripts in VSCode, you might see squiggly lines (indicating issues with your code) and a tab called PROBLEMS at the bottom of the window. These notifications are courtesy of PSScriptAnalyzer, a very versatile PowerShell module that helps to analyze your scripts for issues and errors:
Outside of VSCode, or during a build process, you can use PSScriptAnalyzer by using the exported cmdlets of that module. You can specify which built-in rules and rule sets to apply, as well as exclude certain rules on demand:
# On PS Gallery
Install-Module PSScriptAnalyzer -Force
Get-Command -Module PSScriptAnalyzer
# this triggers the analyzer
# Aliases should not be used
Get-Process | Where Name -eq explorer
# this also triggers a rule
# Variables that are not consumed should be removed
$var = "test"
Invoke-ScriptAnalyzer -Path .Ch5 6_PSScriptAnalyzer.ps1
# you can exclude specific rules
# The argument completer should give you a list of all rules
Invoke-ScriptAnalyzer -Path .Ch5 6_PSScriptAnalyzer.ps1 -ExcludeRule PSAvoidUsingCmdletAliases
When writing your own functions, you can also suppress certain rules inside of those functions. This is very useful if you want to make an exception for your functions, but you will still want to use Invoke-ScriptAnalyzer without any exceptions in your build process. If you don't want this granularity, you can also add the suppression rules for an entire module and all of its functions:
# When writing functions, you can suppress rules as well
function Get-Stuff()
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingWriteHost", "", Justification="I want to write to the console host!")]
param()
Write-Host 'There are no comments here...'
}
Invoke-ScriptAnalyzer -Path .Ch5 6_PSScriptAnalyzer.ps1
You can create PSScriptAnalyzer rules, as well. This is usually done in a module, and is very well documented. However, creating custom rules requires you to analyze the abstract syntax tree (AST) for any violations that you want to flag. The input and output for your custom rules need to follow a specific pattern, documented at https://github.com/PowerShell/PSScriptAnalyzer/blob/development/ScriptRuleDocumentation.md.