r/PowerShell • • 6d ago

Question PowerShell rules for AI coding agent

We know that the default shell for AI coding agents is Bash/Python, but for people like me who use agents on Windows without WSL, I prefer to use PowerShell.

So I wrote these rules for AI coding agents to use PowerShell instead of Bash.

Do you think these rules are OK, or is there anything I might have missed?

# Global Rules

## Shell: PowerShell 7.x (`pwsh`) only

- ALWAYS set `shell_flavor: "powershell"` on `exec` (default is bash). Never use bash/sh/WSL/cmd; never nest shells (`bash -c`, `pwsh -Command`).
- Write PowerShell syntax. Use `workdir` instead of `cd ... &&`. Quote paths with spaces.
- Prefer native cmdlets (`Invoke-RestMethod`, `ConvertFrom-Json`, `Where-Object`, `Select-String`, `Get-ChildItem`, `Test-Path`, `Get-Content`) over `curl`, `jq`, `grep`, `ls`, `cat`, `test`.
- External tools (`git`, `mvn`, `docker`, `npm`) are fine; check `$LASTEXITCODE`.
- Bash → PowerShell: `VAR=x cmd` → `$env:VAR='x'; cmd`; `export` → `$env:`; heredoc → `@'...'@`; `/dev/null` → `$null`; escape char is backtick; single quotes = literal. Quote native args containing `,` or `.` (e.g. `"-Dtest=A,B"`).
- Complex logic: write a `.ps1` (`#Requires -Version 7.0`), never `.sh`.
- Use splatting for many parameters, `Write-Output` (not `Write-Host`), `-Encoding utf8` when writing files, `-LiteralPath` for paths with `[ ]`.
- Confirm with the user before destructive commands (`Remove-Item -Recurse -Force`); preview with `-WhatIf`.

## Token Economy

- Use dedicated `grep`, `find_file_by_name`, `read`, `edit` tools instead of shell for search/read/edit.
- Limit output: `Select-Object -First N`, `Get-Content -Tail N`, `Select-String -Pattern ... -List`/`-Context 0`. Never dump whole files or logs to the shell.
- Return only needed fields: `Select-Object Name,Length`, not full objects. Use `Format-List`/`Format-Table -AutoSize` only at the end and only when needed; avoid wide tables.
- Build/test output (`mvn`, `npm`, `docker`): add quiet flags (`mvn -q -B`, `--no-transfer-progress`, `npm --silent`), then show only failures/summary, e.g. `... 2>&1 | Select-String 'ERROR|FAIL|Tests run:' | Select-Object -Last 30`.
- Save long output to a temp file and read only the relevant lines; do not re-read files already read this session.
- Batch independent commands in one call; chain dependent ones with `&&` or `;`.
- Use `git diff --stat`, `git log --oneline -n 10`, `git status -sb` before full diffs.
- Be concise in replies: no restating the task, no summaries of unchanged code, no unrequested explanations.
6 Upvotes

20 comments sorted by

View all comments

Show parent comment

1

u/MonkeyNin 3d ago

One alternative I would consider to quoting args on native commands: You could instruct it to splat args to native commands with an array.

I recommend that too. My modules call a lot of native commands, and this just makes it easier to not make mistakes.

Plus it's nice being able to conditionally build args. Either in one expression or incrementally.

Encoding

Do you see issues from windows machines defaulting to old encodings, like oem / latin-1, Shift-JS ? I always set commands to use utf8 to prevent decoding errors.

I'm not sure if LLM's are defaulting to the systems culture for local commands? Normally you can fix this in your $Profile.CurrentUserAllHosts .

$OutputEncoding =                                                                             
    [Console]::OutputEncoding = [Console]::InputEncoding =                                    
    [System.Text.UTF8Encoding]::new( <# bool: encoderShouldEmitUTF8Identifier #> $false )     

Example: Splat Arrays to call Git

using namespace System.Collections.Generic

# important: -CommandType Application filters out functions and aliases from overwriting your 'git' command
# -ErrorAction Stop causes it to exit early if the command does not exist.
$script:GitCmd = gcm 'git' -CommandType Application -TotalCount 1 -ea 'stop'

function InvokeGitLog { 
   # calls a native command using conditional arguments in one step

   [CmdletBinding()]
   param( 
     [int] $Limit = 7,
     [object[]] $ArgList = @(),
 
     [switch] $OneLine,
     # don't pause 'git log's output
     [switch] $NoPager,

     # run commands from a directory without having to 'cd' into them
     [Alias('Directory', 'GitRepoRoot')]
     [string] $FromPath
   ) 
   # tip: for more control, instead use a:
   #      [List[Object]] $GitArgs = @() 

   $BinArgs = @(
        if( -not [string]::IsNullOrWhiteSpace( $FromPath ) ) { 
            '-C', $FromPath
        }
        if( $NoPager ) { '--no-pager' }
        'log'
        '-n', $Limit
        if( $ArgList.count -gt 0 ) { $ArgList }
        if( $OneLine ) { '--oneline' }
   )
   & $script:GitCmd @binArgs
   $binArgs -join ' ' | Write-Verbose # show actual args that were used

   # git --no-pager log HEAD~3..HEAD~1 --oneline
} 

InvokeGitLog
InvokeGitLog -Verbose -NoPager -ArgList 'HEAD~3..HEAD~1' -OneLine
InvokeGitLog -Verbose -NoPager 'v2.0.0' -Limit 3 -FromPath ./psreadline -OneLine

1

u/OPconfused 3d ago

Now that you mention it, i have had issues with line endings. The LLM fixes it, but it costs corrections and rarely also fails. I havent had any encoding issues afaik. But i am programming in java so i think it assumes all the encoding as utf8.