ps/Modules/Alkami.PowerShell.PSScriptAnalyzerRules/Public/Measure-CmdletBinding.ps1

67 lines
2.4 KiB
PowerShell
Raw Permalink Normal View History

2023-05-30 22:51:22 -07:00
function Measure-CmdletBinding {
<#
.SYNOPSIS
Add CmdletBinding to your function.
.DESCRIPTION
The CmdletBinding attribute is an attribute of functions that makes them operate like compiled cmdlets written in C#. It provides access to the features of cmdlets.
You can get more details by running: Get-Help about_Functions_CmdletBinding_Attribute
.EXAMPLE
Measure-CmdletBinding -FunctionDefinitionAst $FunctionDefinitionAst
.INPUTS
[System.Management.Automation.Language.FunctionDefinitionAst]
.OUTPUTS
[Microsoft.Windows.Powershell.ScriptAnalyzer.Generic.DiagnosticRecord[]]
.NOTES
Reference: Writing Help and Comments, Windows PowerShell Best Practices.
#>
[CmdletBinding()]
[OutputType([Microsoft.Windows.Powershell.ScriptAnalyzer.Generic.DiagnosticRecord[]])]
Param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.Language.FunctionDefinitionAst]
$FunctionDefinitionAst
)
Process {
$results = @()
$message = (Get-Help $MyInvocation.MyCommand.Name).Synopsis
try {
#region Define predicates to find ASTs.
# Finds CmdletBinding attribute.
[ScriptBlock]$predicate = {
param ([System.Management.Automation.Language.Ast]$Ast)
[bool]$returnValue = $false
if ($Ast -is [System.Management.Automation.Language.AttributeAst]) {
[System.Management.Automation.Language.AttributeAst]$attrAst = $ast;
if ($attrAst.TypeName.Name -eq 'CmdletBinding') {
$returnValue = $true
}
}
return $returnValue
}
#endregion
# Find if the function does not have CmdletBinding attribute
[System.Management.Automation.Language.AttributeAst[]]$attrAsts = $FunctionDefinitionAst.Find($predicate, $true)
if (!$attrAsts) {
$result = New-Object `
-Typename "Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.DiagnosticRecord" `
-ArgumentList $message,$FunctionDefinitionAst.Extent,$PSCmdlet.MyInvocation.InvocationName,Warning,$null
$results += $result
}
return $results
} catch {
$PSCmdlet.ThrowTerminatingError($PSItem)
}
}
}