Skip to content

Instantly share code, notes, and snippets.

@Jaykul
Created January 11, 2017 21:46
Show Gist options
  • Save Jaykul/e58b5820d7ca3d3d681f5605d8e136cd to your computer and use it in GitHub Desktop.
Save Jaykul/e58b5820d7ca3d3d681f5605d8e136cd to your computer and use it in GitHub Desktop.
Custom PSScriptAnalyzer Rules
<#
.SYNOPSIS
Do not use underscores in command names
.DESCRIPTION
You should not use underscores in PowerShell command names
To fix a violation of this rule, rename your command to remove underscores.
.EXAMPLE
Measure-UnderscoreNotAllowedInFunctionName -ScriptBlockAst $ScriptBlockAst
.INPUTS
[System.Management.Automation.Language.ScriptBlockAst]
.OUTPUTS
[Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.DiagnosticRecord[]]
.NOTES
None
#>
function Measure-UnderscoreNotAllowedInFunctionName
{
[CmdletBinding()]
[OutputType([Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.DiagnosticRecord[]])]
Param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.Language.ScriptBlockAst]
$ScriptBlockAst
)
Process
{
[Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.DiagnosticRecord[]]$results = @()
try
{
#region Define predicates to find ASTs.
[ScriptBlock]$functionDefinitionWithUnderScores = {
param ([System.Management.Automation.Language.Ast]$Ast)
[bool]$returnValue = $false
if ($funcAst = $Ast -as [System.Management.Automation.Language.FunctionDefinitionAst])
{
# members are part of a class, this rule only applies to bare functions
if ($funcAst.Parent -is [System.Management.Automation.Language.MemberAst])
{
return $false
}
if ($funcAst.Name -match "_")
{
return $true
}
}
}
#endregion
#region Finds ASTs that match the predicates.
[System.Management.Automation.Language.Ast[]]$functionAst = $ScriptBlockAst.FindAll($functionDefinitionWithUnderScores, $true)
if (($functionAst.Count -ne 0))
{
foreach($extent in $functionAst.Extent) {
$result = [Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.DiagnosticRecord]@{
'Message' = "Command name '$($functionAst.Name)' should not contain underscores"
'Extent' = $Extent
'RuleName' = $PSCmdlet.MyInvocation.InvocationName -replace "Measure-"
'Severity' = 'Warning'
}
$results += $result
}
}
return $results
#endregion
}
catch
{
$PSCmdlet.ThrowTerminatingError($_)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment