Skip to main content
rule CX Codex

powershell · microsoft — Claude Code rule for PowerShell scripts

This rule sets conventions for PowerShell scripts, modules, and data files. Claude Code applies them to .ps1, .psm1, and .psd1 files.

MIT ★ 1,627 updated 2026-10-25

Install into GitHub Copilot · Manually: put the files in place All methods and platforms ↓
.github/instructions/powershell.instructions.md
Open on GitHub

What powershell does

The rule specifies a script layout with a copyright header, #Requires -Version 7.4, comment-based help, typed parameters, and error handling. A .ps1 file needs a shebang. Its main logic runs behind an invocation check, so Pester tests can dot-source the file without triggering that logic.

Modules have separate conventions: functions need help and attributes, and exports must be explicit. Class-only modules use using module in consumers. Function names follow Verb-Noun PascalCase. The required version is PowerShell 7.4, so scripts written to this rule will not meet its requirements on older versions.

What it helps with

  • structure a PowerShell script consistently
  • define typed parameters and error handling
  • export module functions explicitly
  • keep main logic from running during dot-sourcing

Example prompts for the agent

  • Create a PowerShell file-checking script with parameters and error handling that follows this rule.
  • Update this .psm1 module to match the project conventions and export its functions explicitly.
  • Make the main logic in this .ps1 run only when the file is invoked directly.

How to install powershell

Manually: put the files in place

.github/instructions/powershell.instructions.md

The applyTo field sets which files it applies to

Step by step, with commands for each platform: AGENTS.md vs CLAUDE.md: what they are and which one to use

Questions about powershell

How do I install powershell in Claude Code?

Add the rule file at .claude/rules/powershell.md.

What does the powershell rule do?

It defines conventions for PowerShell scripts, modules, and data files, including structure, parameters, error handling, and function exports.

Which PowerShell version does this rule require?

Scripts and modules must include #Requires -Version 7.4.

Source text

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

Similar IDE rules

IDE rules catalog →

powershell by other authors comes first.

powershell official github A GitHub Copilot rule that pushes it toward idiomatic PowerShell scripts following Microsoft's cmdlet guidelines. Useful when your repo has .ps1 and .psm1 files. CX Codex +1 ★ 41,430repo stars powershell-master JosiahSiegel powershell-master — a skill for PowerShell work: cmdlet syntax, PSGallery modules, CI/CD pipeline patterns and security. Useful whenever the agent writes a .ps1 or edits a pipeline. CX Codex +1 1,200installs analyzing-powershell-script-block-logging mahipal The analyzing-powershell-script-block-logging skill parses PowerShell Script Block Logging events from EVTX files and flags obfuscated commands, Base64 payloads and AMSI bypass attempts. CX Codex +1 313installs analyzing-powershell-empire-artifacts mahipal The analyzing-powershell-empire-artifacts skill hunts for PowerShell Empire traces in Windows event logs and builds a report with IOCs, decoded payloads, and MITRE ATT&CK mappings. CX Codex +1 303installs powershell-7-expert VoltAgent Community powershell-7-expert builds cross-platform PowerShell 7+ scripts for Azure, Microsoft Graph, and CI/CD pipelines with .NET 6/7 interop. CX Codex 256installs powershell-ui-architect VoltAgent Community powershell-ui-architect designs desktop graphical interfaces (WinForms, WPF, Metro) and terminal UIs for PowerShell tools while keeping business logic separate. CX Codex 218installs powershell-shell-detection JosiahSiegel powershell-shell-detection is a Claude Code skill that identifies whether a script runs in PowerShell, Git Bash/MSYS2, or cmd. It helps with Windows paths and command invocation across shells. CX Codex +1 211installs

From the same set148

The whole set →
rpi-plan-critique rpi-plan-critique is a Claude Code skill that independently reviews RPI implementation plans without editing them, checking task credibility against supplied evidence before coding begins. CX Codex +1 ★ 1,627repo stars DT Learning Tutor DT Learning Tutor — a tutor subagent that walks you through Design Thinking: nine methods, comprehension checks between modules, pacing that follows your level. CX Codex +1 ★ 1,627repo stars experiment-design experiment-design — a reference pack for running experiments: turning unknowns into testable hypotheses, screening out non-experiments, and keeping scope tight enough for decision-ready results. CX Codex +1 ★ 1,627repo stars video-to-gif video-to-gif converts video clips into optimized animated GIFs using two-pass FFmpeg palette generation. Useful for crafting UI demos and docs previews directly inside the CLI. CX Codex +1 ★ 1,627repo stars PowerPoint Subagent PowerPoint Subagent executes PowerPoint operations: extracts slide content to YAML, builds decks from YAML and styles, validates quality using vision checks. Use it to automate presentation creation in Claude Code. CX Codex +1 ★ 1,627repo stars hve-slides hve-slides is a Claude Code skill for creating, updating, and auditing interactive HTML presentations in HVE Core, with presenter controls and keyboard navigation. CX Codex +1 ★ 1,627repo stars licensing-posture The licensing-posture rule guides how contributors quote, paraphrase, and attribute third-party standards. It applies to reference material in skills and .copilot-tracking. CX Codex +1 ★ 1,627repo stars Skill Assessor Skill Assessor is a Claude Code subagent that scans code for vulnerabilities against OWASP, Secure by Design, and MCSB. It reports findings with statuses and fix examples. CX Codex +1 ★ 1,627repo stars

Project sponsors

Companies that keep this analytics open