While writing some PowerShell Pester tests for my module AdsiPS, I wanted to make sure for each functions that all the help keywords of the comment based help were not indented.

Depending of the script editor you are using, the number of spaces or tabs might differ and once published on GitHub the code might looks not so pretty.

My goal is just to keep my code clean and enforce the same practice across all the functions.

Example

Here for example, I don’t want this:

Instead, I want all the comment based help in that format

(Help keywords directly at the beginning of the line)

Code

This can be accomplish by something like that:

[ CmdletBinding ()] PARAM ( $ModuleName = "ADSIPS" , $GithubRepository = "github.com/lazywinadmin/" ) # Make sure one or multiple versions of the module are note loaded Get-Module -Name $ModuleName | remove-module # Find the Manifest file $ManifestFile = " $( Split-path ( Split-Path -Parent -Path $MyInvocation . MyCommand . Definition )) \ $ModuleName \ $ModuleName . psd1 " # Import the module and store the information about the module $ModuleInformation = Import-module -Name $ManifestFile -PassThru # Get the functions present in the Manifest $ExportedFunctions = $ModuleInformation .ExportedFunctions.Values.name # Testing the Module Describe " $ModuleName Module - HELP " -Tags " Module " { # $Commands = (get-command -Module ADSIPS).Name FOREACH ( $funct in $ExportedFunctions ) { # Retrieve the content of the current function $FunctionContent = Get-Content function: $funct Context " $funct - Comment Based Help - Indentation Checks "{ # Validate Help start at the beginning of the line It " Help - Starts at the beginning of the line "{ $Pattern = " . Synopsis " ( $FunctionContent -split '\r

' | select-string $Pattern ).line -match " ^ $Pattern " | Should Be $true } } } }

Step By Step

So what is happening here ?

#1 - I get the content of the function using Get-Content

$FunctionContent = Get-Content function: $funct

#2 - I define the pattern that I want to retrieve, here I’m just looking for the help keyword Synopsis

$Pattern = ".Synopsis"

I guess i could check each help keywords as an improvement of the current code.

#3 - I split the content of the Function file on each Carriage Return character and look for the pattern I define in #2. This will give me any lines that contains .Synopsis (We should only have one)

$FunctionContent -split '\r

' | select-string $Pattern

#4 - Using regex, we specify the caret character ^ which will matches the beginning of a line with the pattern we defined. Finally we validate that it is $true using the Pester syntax Should Be

line -match "^ $Pattern " | Should Be $true

Related posts