Thursday, March 28, 2024
HomePowershellUse the Summary Syntax Tree (AST) to record parameters and variables in...

Use the Summary Syntax Tree (AST) to record parameters and variables in PowerShell capabilities · Mike F. Robbins


One factor I’ve missed through the previous couple of years with virtual-only conferences is the hallway
observe. Whereas on the PowerShell + DevOps World Summit 2022, there was a dialogue about utilizing
PascalCase for parameter names and camelCase for user-defined variables in your PowerShell
capabilities.

Specifying completely different casings relying on the utilization looks as if an incredible concept. Figuring out the place you
outlined your variables could be self-explanatory. The one downside is you want one thing to confirm
that you just’ve specified them within the right case.

This situation is an ideal alternative to make use of the Summary Syntax Tree (AST) to confirm the casing is
right relying on utilization.

I began utilizing the Get-MrAst perform in my
MrModuleTools PowerShell module from my
ModuleTools GitHub repo to retrieve the AST from a
file or script block.

Get-MrAst -Path C:MrGitInspectorMrInspectorpublicGet-MrSyntax.ps1

I used one other one in all my capabilities named Get-MrAstType in the identical module to find out the
completely different choices for filtering the AST. This half was easy since they’re named
ParameterAst and VariableExpressionAst.

Get-MrAstType | Format-Vast -Property {$_} -Column 3 -Drive

variable-type2a.jpg

There are two alternative ways to acquire the parameters and variables. One accommodates the greenback signal
and the opposite, solely the variable identify. I opted for the one with solely the variable identify. I filtered
out the underscore to forestall present object variables from displaying up within the record until you’re
utilizing PSItem.

The record of variables additionally accommodates the parameters as a result of they’re specified within the physique of the
perform. I used Examine-Object to find out which objects are duplicated in each lists. An If
assertion identifies the duplicates as parameters and the non-duplicated objects as user-defined
variables.

I included the road and column numbers within the output to know the place the variables are used. Generally
they’re specified greater than as soon as on the identical line.

#Requires -Model 4.0
perform Get-MrVariableType {

<#
.SYNOPSIS
    Checklist variables and whether or not they're outlined as parameters or within the physique of a perform.

.DESCRIPTION
    Get-MrVariableType is a complicated perform that returns a listing of variables outlined in a
    perform and whether or not they're parameters or consumer outlined inside the physique of the perform.

 .PARAMETER Ast
    Present a ScriptBlockAst object by way of parameter or pipeline enter. Use Get-MrAst to create this
    object.

.EXAMPLE
     Get-MrAST -Path 'C:Scripts' | Get-MrVariableType

.EXAMPLE
     Get-MrVariableType -Ast (Get-MrAST -Path 'C:Scripts')

.NOTES
    Creator:  Mike F Robbins
    Web site: http://mikefrobbins.com
    Twitter: @mikefrobbins
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory,
                   ValueFromPipeline)]
        [System.Management.Automation.Language.ScriptBlockAst]$Ast
    )

    PROCESS {

        $variables = $Ast.FindAll({$args[0].GetType().Title -like 'VariableExpressionAst'}, $true).The place({$_.VariablePath.UserPath -ne '_'})

        $parameters = $Ast.FindAll({$args[0].GetType().Title -like 'ParameterAst'}, $true)

        $diff = Examine-Object -ReferenceObject $parameters.Title.VariablePath.UserPath -DifferenceObject $variables.VariablePath.UserPath -IncludeEqual

        foreach ($variable in $variables) {

            [pscustomobject]@{
                Title = $variable.VariablePath.UserPath
                Kind = if ($variable.VariablePath.UserPath -in $diff.The place({$_.SideIndicator -eq '=='}).InputObject) {
                           'Parameter'
                       } else {
                           'UserDefined'
                       }
                LineNumber = $variable.Extent.StartLineNumber
                Column = $variable.Extent.StartColumnNumber
            }

        }

    }

}

You possibly can pipe the output of Get-MrAst to Get-MrVariableType or present the outcomes by way of parameter
enter with the Ast parameter.

Get-MrAst -Path C:MrGitInspectorMrInspectorpublicGet-MrSyntax.ps1 |
Get-MrVariableType

variable-type3a.jpg

You may as well kind the output with Kind-Object to see the place you’ve specified variables in a
completely different case. Discover the variations with the file and true variables within the following outcomes.

Get-MrAst -Path C:MrGitInspectorMrInspectorpublicGet-MrSyntax.ps1 |
Get-MrVariableType |
Kind-Object -Property Title

variable-type4a.jpg

You possibly can write a unit check utilizing Pester to id when parameters and
variables don’t adhere to your requirements. You possibly can additionally write code that makes use of the output of
Get-MrVariableType to automate the remediation of variable casing.

The Get-MrVariableType perform proven on this weblog article is a part of my
MrModuleTools PowerShell module. You
can set up it from the PowerShell Gallery utilizing the next command:

Set up-Module -Title MrModuleTools

The video proven under demonstrates use the
Get-MrVariableType perform.

You possibly can obtain the supply code from my
ModuleTools GitHub repo. Be at liberty to submit a GitHub
subject when you have recommendations or discover issues. I settle for pull requests if you want to
contribute.

µ

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments