Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add analyzerrule for highlighting slow *-object commands #1753

Merged
merged 1 commit into from
Jun 14, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
63 changes: 63 additions & 0 deletions Pester.BuildAnalyzerRules/Pester.BuildAnalyzerRules.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,67 @@ function Measure-SafeComands {
}
}

Function Measure-ObjectCmdlets {
<#
.SYNOPSIS
Should avoid usage of New/Where/Foreach/Select-Object.
.DESCRIPTION
The built-in *-Object-cmdlets are slow compared to alternatives in .NET. To fix a violation of this rule, consider using an alterantive like `foreach`-keyword etc.`.
.EXAMPLE
Measure-ObjectCmdlets -CommandAst $CommandAst
.INPUTS
[System.Management.Automation.Language.CommandAst]
.OUTPUTS
[Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.DiagnosticRecord[]]
.NOTES
None
#>
[CmdletBinding()]
[OutputType([Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.DiagnosticRecord[]])]
Param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.Language.CommandAst]
$CommandAst
)

Process {
$results = @()

#StringConstantExpressionAst match (direct cmdlet usage)
$objectCommands = "(?:New|Where|Foreach|Select)-Object"

$result = [Microsoft.Windows.PowerShell.ScriptAnalyzer.Generic.DiagnosticRecord]@{
'Message' = "$((Get-Help $MyInvocation.MyCommand.Name).Description.Text)"
'Extent' = $CommandAst.Extent
'RuleName' = $PSCmdlet.MyInvocation.InvocationName
'Severity' = 'Information'
}

try {
$commandName = $CommandAst.GetCommandName()

if ($null -ne $commandName -and $commandName -match $objectCommands) {
# Cmdlet used
$results += $result

} elseif ($CommandAst.InvocationOperator -eq [System.Management.Automation.Language.TokenKind]::Ampersand) {
$invocatedCmd = $CommandAst.CommandElements[0]

if ($invocatedCmd -is [System.Management.Automation.Language.IndexExpressionAst] -and
$invocatedCmd.Target -match 'SafeCommands'-and $invocatedCmd.Index -match $objectCommands) {
# SafeCommands
$results += $result
}
}

return $results
}
catch {
$PSCmdlet.ThrowTerminatingError($PSItem)
}
}
}

Export-ModuleMember -Function 'Measure-*'