PowerShell / PowerShell/PSScriptAnalyzer

Rule request: AvoidUsingBacktickLineTerminator

Abierto
#2,111 1 comentario 3 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Lenguaje dominante
C#
Estrellas
2.2k
Forks
414
Merge medio
13 h 1 min
PR fusionados (30 d)
2

Descripción

Summary of the new feature

As a code reviewer, I want script/module writers to receive automated informational warnings about backtick usage so that my review time isn't consumed by catching maintainability issues that tooling should prevent upfront.

Problem Statement:
The backtick (`) character is commonly used for line continuation in PowerShell, but it's considered poor practice for several reasons:

  • Hard to see: Backticks are nearly invisible and easily missed during code review
  • Poor readability: Makes code harder to read and understand
  • Maintenance issues: Easy to accidentally remove or misplace during editing
  • Non-intuitive: New PowerShell users often struggle with backtick usage

PowerShell offers better alternatives like parameter splatting and natural line breaks after operators/pipelines that are more readable and less error-prone.

Proposed technical implementation details

Rule Name: PSAvoidUsingBacktickLineTerminator

Severity: Information

Behavior:

  • Flag any usage of backtick (`) character used for line continuation
  • Suggest appropriate alternatives based on context

Recommended alternatives to suggest:

  1. Parameter Splatting: For commands with multiple parameters
  2. Natural line breaks: After pipeline operators (|), logical operators (-and, -or), comparison operators
  3. Parentheses grouping: For complex expressions

Example violations:

# Backtick line continuation - Flagged
Get-Process -Name notepad `
    -ErrorAction SilentlyContinue `
    | Where-Object CPU -gt 100

# Complex command with backticks - Flagged  
$result = Get-ChildItem -Path C:\Temp `
    -Filter "*.txt" `
    -Recurse `
    -ErrorAction SilentlyContinue

Technical Implementation:

  • I plan on taking this issue if approved.
  • Simple class that inherits ITokenRule:
public IEnumerable<DiagnosticRecord> AnalyzeTokens(Token[] tokens, string fileName)
{
    if (tokens == null) throw new ArgumentNullException(Strings.NullTokensErrorMessage);

    var lineContinuationTokens = tokens.Where(token => token.Kind == TokenKind.LineContinuation);

    foreach (var tokenNode in lineContinuationTokens)
    {
        yield return new DiagnosticRecord(
            string.Format(CultureInfo.CurrentCulture, Strings.AvoidUsingBacktickLineTerminatorError),
            tokenNode.Extent,
            GetName(),
            DiagnosticSeverity.Information,
            fileName
        );
    }
}

What is the latest version of PSScriptAnalyzer at the point of writing

1.24.0

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Comienza examinando las implementaciones existentes de ITokenRule y el punto de entrada AnalyzeTokens descrito en el issue, especialmente TokenKind.LineContinuation y el mensaje de diagnóstico en Strings. Confirma cómo se registran y prueban las reglas comparables. Se considera terminado cuando los tokens de continuación de línea con backticks producen diagnósticos informativos con el nombre de la regla y el intervalo de origen, sin marcar tokens no relacionados.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
csharp, powershell
Área
tooling
Tipo de issue
Nueva funcionalidad
Dificultad
3/5
Tiempo estimado
1-2 días
Estado de actividad
Tranquilo
Claridad
Bastante claro
Aptitud para principiantes
58/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.