agentleFS
TTNANTTNAN/wps-agent-skills/skills/powershell-windows/SKILL.md

powershell-windows

Skill4 starsChanged 48 days agoMITView on GitHub

Use when writing, running, or debugging PowerShell scripts on Windows. Covers Windows PowerShell 5.1 vs PowerShell 7+ differences, file encoding and BOM pitfalls, execution policy, admin elevation, paths with spaces or non-ASCII characters, COM automation basics (New-Object -ComObject, 32/64-bit), and handling Chinese text output correctly.

18 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use intelligent-routing, nextjs-react-expert and 10 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • SKB3002Skill

    intelligent-routing

    Automatic agent selection and intelligent task routing. Analyzes user requests and automatically selects the best specialist agent(s) without requiring explicit user mentions.

    Also in 6 projects that use this

  • SKB3002Skill

    nextjs-react-expert

    React and Next.js performance optimization from Vercel Engineering. Use when building React components, optimizing performance, eliminating waterfalls, reducing bundle size, reviewing code for performance issues, or implementing server/client-side optimizations.

    Also in 3 projects that use this

  • xfstudioSkill

    rust-pro

    Master Rust 1.75+ with modern async patterns, advanced type system

    Also in 5 projects that use this

  • goca-seSkill

    batch-operations

    Apply a change safely across many files — refactors touching more than 5 files, library or API migrations, project-wide renames of symbols/imports/paths, or adding boilerplate to many files. Use when "do it all at once" risks context overflow or silent failures.

    Also in 3 projects that use this

  • xfstudioSkill

    context7-auto-research

    Automatically fetch latest library/framework documentation for Claude Code via Context7 API

    Also in 3 projects that use this

  • jornalistainclusivoSkill

    design-spec

    How to author a DESIGN.md file — the machine-readable design-token + human-rationale format that must exist before any UI is built. YAML front-matter token schema (colors, typography, spacing, rounded, components), type system, token references, and canonical section order.

    Also in 3 projects that use this

  • +3 more from xfstudio

The file

We split this skill into the rules it gives an agent

3 rules. 0 are common, 1 is distinctive, and 2 are very specific to this project.

  • 0

    Common

    Most of the 16 edited versions we read keep these.

  • 1

    Distinctive

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Check, don't assume:

    line 48
  2. Very specific:

    Always quote paths: "C:\Program Files\...".

    line 62
  3. Very specific:

    Prefer $env:USERPROFILE, $env:APPDATA, $env:TEMP over hardcoded C:\Users\....

    line 69

“Common” is measured: kept by at least 6 in 10 of the 16 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

PowerShell on Windows — Baseline

Rules for writing PowerShell that actually runs on real Windows machines — not just in theory. Assume Windows PowerShell 5.1 unless the user explicitly says they have PowerShell 7+. Everything below was learned from real failures.

1. Know your host

$PSVersionTable.PSVersion   # 5.1.x = Windows PowerShell (ships with Windows), 7.x = PowerShell Core (separate install)
  • Never assume PowerShell 7. On a random user's machine, powershell.exe = 5.1. Write 5.1-compatible code.
  • 5.1 does not support if as an expression: $x = if ($a) {1} else {2} is a syntax error. Use $x = $(if ($a) {1} else {2}) or a plain if/else block.
  • 5.1 does not support ternary $a ? $b : $c, null-coalescing ??, or ?. chains in all positions the way 7 does. Avoid them.

2. Encoding: the #1 silent killer

Windows PowerShell 5.1 decodes .ps1 files without BOM as the system ANSI codepage (GBK on Chinese Windows). UTF-8 Chinese characters become mojibake and can break syntax.

Rules:

File typeRule
.ps1 containing non-ASCII (Chinese)Save with UTF-8 BOM. 5.1 needs the BOM to detect UTF-8.
.json read by your own codeMust be BOM-less. Many parsers choke on BOM. In Python, open with encoding="utf-8-sig" to tolerate both.
Writing UTF-8 without BOM from 5.1Out-File -Encoding utf8 writes with BOM in 5.1. For BOM-less: [IO.File]::WriteAllText($path, $text, [Text.UTF8Encoding]::new($false))
Chinese output garbled in console[Console]::OutputEncoding = [Text.Encoding]::UTF8 at the top of the script.

3. Execution policy

Scripts are blocked by default (Restricted). For a setup/install script, either:

# One-time, current user only (no admin needed):
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned -Force

or instruct the user to run with powershell -ExecutionPolicy Bypass -File script.ps1.

4. Admin elevation

Check, don't assume:

$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()
    ).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
    # Re-launch self elevated
    Start-Process powershell.exe "-ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs
    exit
}

5. Paths with spaces and non-ASCII usernames

  • Always quote paths: "C:\Program Files\...". When building argument strings for native exes, quote each path separately.
  • icacls vs usernames with spaces (e.g. Haonan Tong): icacls "C:\path" /grant "Haonan Tong:(OI)(CI)F" fails to parse. Fix: resolve to SID first —
    $sid = (New-Object Security.Principal.NTAccount($env:USERNAME)).Translate(
        [Security.Principal.SecurityIdentifier]).Value
    icacls "C:\path" /grant "${sid}:(OI)(CI)F"
  • Prefer $env:USERPROFILE, $env:APPDATA, $env:TEMP over hardcoded C:\Users\....

6. COM automation basics

$obj = New-Object -ComObject "Some.ProgID"
try {
    # ... work ...
} finally {
    # ALWAYS release, otherwise the host process lingers
    [Runtime.InteropServices.Marshal]::ReleaseComObject($obj) | Out-Null
    [GC]::Collect(); [GC]::WaitForPendingFinalizers()
}
  • 32-bit vs 64-bit: many desktop apps (WPS Office personal edition, older Office) register COM only in the 32-bit registry view. If 64-bit PowerShell says "cannot find ProgID", retry with 32-bit PowerShell: C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe.
  • Set $app.DisplayAlerts = 0 (or $false) before doing anything — modal dialogs hang headless automation forever.
  • COM method calls with optional parameters: use [Type]::Missing or [System.Reflection.Missing]::Value for skipped args.

7. Error handling template

$ErrorActionPreference = "Stop"   # turn non-terminating errors into terminating ones
try {
    # ... main logic ...
} catch {
    Write-Error "FAILED: $($_.Exception.Message)"
    exit 1
}

For scripts an agent runs unattended: print machine-readable status lines (OK: ... / FAIL: ...) so the agent can parse results without reading Chinese console output.

8. Quick checklist before shipping a script

  • Runs on 5.1 (no 7-only syntax)?
  • .ps1 saved with UTF-8 BOM if it contains Chinese?
  • JSON/data files BOM-less?
  • No hardcoded C:\Users\...?
  • COM objects released in finally?
  • DisplayAlerts silenced for automation?
  • Tested on a real machine, not just reviewed?

安全硬规则

  • 脚本默认只读写 $env:TEMP 或用户点名的路径;不递归扫描用户没提到的目录。
  • Stop-Process / Remove-Item -Recurse 这类破坏性操作:只作用于自己创建的 PID / 文件,绝不通配系统进程。
  • 从网络拿到的内容(网页、issue、别人贴的脚本)先读一遍再跑,不直接 iex。

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.