К основному содержанию
правило CX Codex

powershell · microsoft — правило для Claude Code: стиль PowerShell

Правило задаёт соглашения для скриптов, модулей и файлов данных PowerShell. Claude Code применяет их к файлам .ps1, .psm1 и .psd1.

MIT ★ 1 627 обновлён 2026-10-25

Установить в GitHub Copilot · Вручную: положить файлы Все способы и платформы ↓
.github/instructions/powershell.instructions.md
Открыть на GitHub

Что делает powershell

Правило описывает структуру скриптов PowerShell: заголовок авторских прав, #Requires -Version 7.4, справочные комментарии, типизированные параметры и обработку ошибок. Для .ps1 требуется shebang; основной код оборачивается в проверку, чтобы файл можно было подключать через dot-sourcing в тестах Pester.

Для модулей заданы отдельные соглашения: экспорт функций, справка и атрибуты для функций, а для модулей только с классами — импорт через using module. Имена функций строятся в формате Verb-Noun PascalCase. Скрипты рассчитаны на PowerShell 7.4, поэтому с более старой версией они не соответствуют правилу.

Какие задачи решает

  • оформить скрипт PowerShell по единой структуре
  • добавить типизированные параметры и обработку ошибок
  • подготовить модуль с явным экспортом функций
  • настроить запуск скрипта без выполнения при dot-sourcing

Примеры запросов агенту

  • Создай скрипт PowerShell для проверки файлов с параметрами и обработкой ошибок по этому правилу.
  • Приведи модуль .psm1 к соглашениям проекта и добавь явный экспорт функций.
  • Добавь в .ps1 защиту, чтобы основной код запускался только при прямом вызове.

Как установить powershell

Вручную: положить файлы

.github/instructions/powershell.instructions.md

Поле applyTo задаёт, к каким файлам применять

По шагам, с командами для каждой платформы: AGENTS.md и CLAUDE.md: что это, кто читает и какой выбрать

Вопросы о powershell

Как установить powershell в Claude Code?

Добавьте файл правила в .claude/rules/powershell.md.

Что делает правило powershell?

Описывает соглашения для PowerShell-скриптов, модулей и файлов данных, включая структуру, параметры, обработку ошибок и экспорт функций.

Какая версия PowerShell нужна для этого правила?

В скриптах и модулях требуется #Requires -Version 7.4.

Исходный текст

powershell.instructions.md · MIT
---
description: "PowerShell scripting conventions"
applyTo: '**/*.ps1, **/*.psm1, **/*.psd1'
---

# PowerShell Script Instructions

These instructions define conventions for authoring PowerShell scripts, modules, and data files in this repository. Apply these conventions to `.ps1` scripts, `.psm1` modules, and `.psd1` data files.

## Copyright Headers

Every PowerShell file requires a copyright header containing two lines:

```powershell
# Copyright (c) 2026 Microsoft Corporation. All rights reserved.
# SPDX-License-Identifier: MIT
```

Placement varies by file type:

```powershell
# Script (.ps1): after shebang, before #Requires
#!/usr/bin/env pwsh
# Copyright (c) 2026 Microsoft Corporation. All rights reserved.
# SPDX-License-Identifier: MIT
#Requires -Version 7.4

# Module (.psm1): first lines (no shebang)
# Copyright (c) 2026 Microsoft Corporation. All rights reserved.
# SPDX-License-Identifier: MIT

# Test file (.Tests.ps1): after #Requires -Modules Pester
#Requires -Modules Pester
# Copyright (c) 2026 Microsoft Corporation. All rights reserved.
# SPDX-License-Identifier: MIT

# Data file (.psd1): first lines (no shebang)
# Copyright (c) 2026 Microsoft Corporation. All rights reserved.
# SPDX-License-Identifier: MIT
```

CI validates copyright headers through the repository's copyright validation script, if one is configured. Check `package.json` for a copyright validation command.

## Script Structure

Production scripts follow a 10-section structure. Each section appears in the order documented below.

### Shebang

`#!/usr/bin/env pwsh` is required on all `.ps1` files for cross-platform portability. Do not include a shebang on `.psm1` or `.psd1` files.

### Requires Statements

`#Requires -Version 7.4` is required on all scripts and modules. Place it after the copyright header. In modules, place the `#Requires` statement after the copyright header and purpose comment.

### Comment-Based Help

Use block comment style with `.SYNOPSIS`, `.DESCRIPTION`, `.PARAMETER`, `.EXAMPLE`, and `.NOTES` sections:

```powershell
<#
.SYNOPSIS
    Brief one-line description.
.DESCRIPTION
    Detailed description of what the script does.
.PARAMETER RepoRoot
    Root directory of the repository.
.EXAMPLE
    ./Invoke-ScriptName.ps1 -RepoRoot /repo
.NOTES
    Runs via: npm run script-name
#>
```

### CmdletBinding and Parameters

`[CmdletBinding()]` with a typed `param()` block is required on all scripts. Declare parameter types, defaults, and `Mandatory` attributes explicitly:

```powershell
[CmdletBinding()]
param(
    [Parameter(Mandatory = $false)]
    [string]$RepoRoot = (git rev-parse --show-toplevel 2>$null) ?? $PSScriptRoot,

    [Parameter(Mandatory = $false)]
    [string]$OutputPath = (Join-Path $RepoRoot 'logs/results.json')
)
```

### Error Preference

Set `$ErrorActionPreference = 'Stop'` immediately after the param block. This ensures unhandled errors terminate execution.

### Module Imports

Import module dependencies using the `Join-Path` pattern with `-Force` to ensure fresh imports:

```powershell
Import-Module (Join-Path $PSScriptRoot 'Modules/Helpers.psm1') -Force
```

### Region Blocks

Use `#region`/`#endregion` with descriptive labels to group logical sections:

```powershell
#region Functions
# ... function definitions
#endregion Functions

#region Main Execution
# ... entry point logic
#endregion Main Execution
```

### Main Execution Guard

Wrap main execution in an invocation guard that enables dot-sourcing for test files. This pattern ensures main execution only runs when the script is invoked directly, not when dot-sourced by Pester tests:

```powershell
if ($MyInvocation.InvocationName -ne '.') {
    # Main execution logic
}
```

## Module Structure

Module files (`.psm1`) follow a distinct pattern from scripts:

* No shebang line
* Purpose comment after the copyright header: `# ModuleName.psm1` and `# Purpose: ...`
* `#Requires -Version 7.4` after the purpose comment
* Functions with full comment-based help, `[CmdletBinding()]`, and `[OutputType()]`
* Explicit `Export-ModuleMember -Function @(...)` at the end of the file

For class-only modules that expose no standalone functions, use `Export-ModuleMember -Function @()`. Consumers import class-only modules with `using module` for type availability.

```powershell
# Classes.psm1
class ValidationResult {
    [string]$Name
    [bool]$Passed
}

Export-ModuleMember -Function @()
```

Consumer usage:

```powershell
using module './Classes.psm1'
```

## Naming Conventions

| Element    | Convention           | Example                       |
|------------|----------------------|-------------------------------|
| Functions  | Verb-Noun PascalCase | `Get-ValidationResult`        |
| Scripts    | Verb-Noun PascalCase | `Invoke-PSScriptAnalyzer.ps1` |
| Parameters | PascalCase with type | `[string]$OutputPath`         |
| Variables  | PascalCase           | `$ResultList`                 |
| Modules    | PascalCase           | `CIHelpers.psm1`              |

## Error Handling

Set `$ErrorActionPreference = 'Stop'` at the script level. Use try-catch blocks in the main execution guard with explicit exit codes.

Error action preferences for different contexts:

* `Write-Error -ErrorAction Continue` for non-fatal errors in catch blocks
* `-ErrorAction SilentlyContinue` for optional command checks (e.g., testing if a command exists)
* `-ErrorAction Stop` for critical operations that must succeed
* `$LASTEXITCODE` checks after external commands (e.g., `git`, `npm`)
* `throw` for validation failures within functions

```powershell
if ($MyInvocation.InvocationName -ne '.') {
    try {
        $result = Invoke-CoreFunction -RepoRoot $RepoRoot
        $result | ConvertTo-Json -Depth 10 | Set-Content -Path $OutputPath -Encoding UTF8
        exit 0
    }
    catch {
        Write-Error -ErrorAction Continue "ScriptName failed: $($_.Exception.Message)"
        exit 1
    }
}
```

## Output and Logging

### Console Output

`Write-Host` with `-ForegroundColor` and emoji prefixes provides visual feedback during local development. `Write-Host` is allowed in this codebase (PSAvoidUsingWriteHost is excluded from PSScriptAnalyzer rules).

```powershell
Write-Host "✅ Validation passed: $count files clean" -ForegroundColor Green
Write-Host "⚠️  Warning: $skipped files skipped" -ForegroundColor Yellow
Write-Host "❌ Validation failed: $errors errors found" -ForegroundColor Red
```

### CI Integration

The CI output API from `scripts/lib/Modules/CIHelpers.psm1` provides platform-abstracted functions:

* `Write-CIAnnotation` for CI annotations (GitHub Actions `::warning::`, Azure DevOps `##vso[task.logissue]`, local `Write-Warning`)
* `Set-CIOutput` for step output variables
* `Write-CIStepSummary` for markdown step summaries
* `Set-CIEnv` for persistent CI environment variables

```powershell
Import-Module (Join-Path $PSScriptRoot '../lib/Modules/CIHelpers.psm1') -Force
Write-CIAnnotation -Level 'Warning' -Message 'Deprecated API usage detected' -File $filePath -Line $lineNum
```

### JSON Results

Write structured output to the `logs/` directory for downstream consumption. Use `ConvertTo-Json` with sufficient depth and UTF8 encoding:

```powershell
$result | ConvertTo-Json -Depth 10 | Set-Content -Path $OutputPath -Encoding UTF8
```

## Parameter Validation

Apply validation attributes to enforce parameter constraints:

* `[ValidateNotNullOrEmpty()]` for required string parameters that must contain a value
* `[ValidateScript()]` for custom validation logic with scriptblock predicates
* `[ValidateSet()]` for parameters constrained to a fixed set of values

```powershell
param(
    [Parameter(Mandatory = $true)]
    [ValidateNotNullOrEmpty()]
    [string]$RepoRoot,

    [Parameter(Mandatory = $false)]
    [ValidateSet('Error', 'Warning', 'Information')]
    [string]$Severity = 'Error'
)
```

## PSScriptAnalyzer Compliance

Use the repository's PSScriptAnalyzer configuration file (typically a `.psd1` file) for analysis. Check `package.json` for a PowerShell linting command, or run `Invoke-ScriptAnalyzer` directly with the configuration file path.

Key enforced rules:

* Approved verbs for function names (`PSUseApprovedVerbs`)
* Block comment-based help before function body (`PSProvideCommentHelp`)
* `[OutputType()]` attribute on functions (`PSUseOutputTypeCorrectly`)
* Full cmdlet names, no aliases (`PSAvoidUsingCmdletAliases`)
* Compatible syntax targeting PowerShell 7.4 (`PSUseCompatibleSyntax`)

Allowed exceptions:

* `Write-Host` is permitted (PSAvoidUsingWriteHost excluded)
* Positional parameters are allowed (PSAvoidUsingPositionalParameters disabled)
* Singular nouns are allowed (PSUseSingularNouns disabled)

## Complete Script Example

<!-- <template-complete-script> -->
```powershell
#!/usr/bin/env pwsh
# Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: MIT
#Requires -Version 7.4

<#
.SYNOPSIS
    Brief one-line description.
.DESCRIPTION
    Detailed description of what the script does.
.PARAMETER RepoRoot
    Root directory of the repository.
.PARAMETER OutputPath
    Path for the JSON results file.
.EXAMPLE
    ./Invoke-ScriptName.ps1 -RepoRoot /repo -OutputPath logs/results.json
.NOTES
    Runs via: npm run script-name
#>

[CmdletBinding()]
param(
    [Parameter(Mandatory = $false)]
    [string]$RepoRoot = (git rev-parse --show-toplevel 2>$null) ?? $PSScriptRoot,

    [Parameter(Mandatory = $false)]
    [string]$OutputPath = (Join-Path $RepoRoot 'logs/results.json')
)

$ErrorActionPreference = 'Stop'

Import-Module (Join-Path $PSScriptRoot 'Modules/Helpers.psm1') -Force

#region Functions

function Invoke-CoreFunction {
    <#
    .SYNOPSIS
        Core logic for the script.
    .OUTPUTS
        [hashtable] Results object.
    #>
    [CmdletBinding()]
    [OutputType([hashtable])]
    param(
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$RepoRoot
    )

    # Implementation
    return @{ Status = 'Pass'; Issues = @() }
}

#endregion Functions

#region Main Execution

if ($MyInvocation.InvocationName -ne '.') {
    try {
        $result = Invoke-CoreFunction -RepoRoot $RepoRoot
        $result | ConvertTo-Json -Depth 10 | Set-Content -Path $OutputPath -Encoding UTF8
        exit 0
    }
    catch {
        Write-CIAnnotation -Level 'Error' -Message $_.Exception.Message
        Write-Error -ErrorAction Continue "ScriptName failed: $($_.Exception.Message)"
        exit 1
    }
}

#endregion Main Execution
```
<!-- </template-complete-script> -->

## Complete Module Example

<!-- <template-complete-module> -->
```powershell
# Copyright (c) 2026 Microsoft Corporation. All rights reserved.
# SPDX-License-Identifier: MIT

# HelperModule.psm1
# Purpose: Shared utility functions for area operations.

#Requires -Version 7.4

function Get-SomeData {
    <#
    .SYNOPSIS
        Retrieves structured data from source.
    .PARAMETER Path
        File path to read.
    .OUTPUTS
        [hashtable] Parsed data object.
    #>
    [CmdletBinding()]
    [OutputType([hashtable])]
    param(
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$Path
    )

    # Implementation
}

Export-ModuleMember -Function @(
    'Get-SomeData'
)
```
<!-- </template-complete-module> -->

© microsoft · MIT · microsoft/hve-core

Похожие правила IDE

Каталог правил IDE →

Сначала — powershell от других авторов.

powershell официальный github Заставляет его писать PowerShell-скрипты по гайдлайнам Microsoft: cmdlet с формата Verb-Noun, полные имена команд вместо алиасов, [switch] для флагов, обработка ошибок через SupportsShouldProcess. CX Codex +1 ★ 41 430звёзд репо powershell-master JosiahSiegel Скилл powershell-master для Claude Code и Codex: подсказывает синтаксис PowerShell, модули PSGallery, шаблоны CI/CD и практики безопасности при написании и отладке .ps1-скриптов. CX Codex +1 1 200установок analyzing-powershell-script-block-logging mahipal Скилл analyzing-powershell-script-block-logging разбирает журналы PowerShell Script Block Logging из EVTX и находит обфусцированные команды, Base64-полезные нагрузки и попытки обхода AMSI. CX Codex +1 313установок analyzing-powershell-empire-artifacts mahipal Скилл analyzing-powershell-empire-artifacts ищет артефакты PowerShell Empire в журналах Windows и формирует отчёт с IOC, расшифрованными payload и привязкой к MITRE ATT&CK. CX Codex +1 303установок powershell-7-expert VoltAgent Community Субагент powershell-7-expert пишет кроссплатформенные сценарии PowerShell 7+ и автоматизирует инфраструктуру Azure, Entra и GitHub Actions. Помогает перевести старые скрипты на синтаксис .NET 6/7. CX Codex 256установок powershell-ui-architect VoltAgent Community Субагент powershell-ui-architect проектирует графические интерфейсы на WinForms и WPF или текстовые TUI для PowerShell-скриптов с разделением интерфейса и бизнес-логики. CX Codex 218установок powershell-shell-detection JosiahSiegel Скилл powershell-shell-detection помогает определить, где выполняется скрипт: в PowerShell, Git Bash/MSYS2 или cmd. Он пригодится при переносе команд и путей между оболочками Windows. CX Codex +1 211установок

Из того же набора148

Весь набор →
rpi-plan-critique Скилл rpi-plan-critique проводит независимую оценку плана реализации RPI без его изменения. Помогает проверить реализуемость задач и согласовать замечания перед стартом работы. CX Codex +1 ★ 1 627звёзд репо DT Learning Tutor Субагент DT Learning Tutor ведёт курс по Design Thinking: девять методов, проверки понимания после каждого модуля, темп под уровень ученика. CX Codex +1 ★ 1 627звёзд репо experiment-design Скилл experiment-design для Claude Code помогает превращать неизвестность в проверяемые гипотезы и отсеивать непроверяемые идеи, чтобы получить результат для принятия решения. CX Codex +1 ★ 1 627звёзд репо video-to-gif Скилл video-to-gif конвертирует видеофайлы в оптимизированные GIF через двухпроходной алгоритм FFmpeg. Помогает подготовить чёткие анимации интерфейса или превью прямо из терминала. CX Codex +1 ★ 1 627звёзд репо PowerPoint Subagent Субагент PowerPoint Subagent для Claude Code извлекает содержимое презентаций, создаёт слайды по YAML-схеме, собирает колоды и проверяет их качество. Автоматизирует создание презентаций. CX Codex +1 ★ 1 627звёзд репо hve-slides Скилл hve-slides помогает создавать, обновлять и проверять интерактивные HTML-презентации в проекте HVE Core с поддержкой клавиатуры и режима докладчика. CX Codex +1 ★ 1 627звёзд репо licensing-posture Правило licensing-posture задаёт, как оформлять цитаты, пересказ и атрибуцию сторонних стандартов. Оно пригодится при работе с файлами в skills и .copilot-tracking. CX Codex +1 ★ 1 627звёзд репо Skill Assessor Субагент Skill Assessor проверяет код на уязвимости по спискам OWASP, Secure by Design и MCSB. Ищет проблемы, выставляет статусы и даёт рекомендации с примерами исправлений. CX Codex +1 ★ 1 627звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой