home / skills / vudovn / antigravity-kit / powershell-windows

powershell-windows skill

/.agent/skills/powershell-windows

This skill helps you write robust PowerShell scripts for Windows by enforcing ASCII-only code, proper parentheses, null checks, and safe error handling.

npx playbooks add skill vudovn/antigravity-kit --skill powershell-windows

Review the files below or copy the command above to add this skill to your agents.

Files (1)
SKILL.md
3.4 KB
---
name: powershell-windows
description: PowerShell Windows patterns. Critical pitfalls, operator syntax, error handling.
allowed-tools: Read, Write, Edit, Glob, Grep, Bash
---

# PowerShell Windows Patterns

> Critical patterns and pitfalls for Windows PowerShell.

---

## 1. Operator Syntax Rules

### CRITICAL: Parentheses Required

| ❌ Wrong | ✅ Correct |
|----------|-----------|
| `if (Test-Path "a" -or Test-Path "b")` | `if ((Test-Path "a") -or (Test-Path "b"))` |
| `if (Get-Item $x -and $y -eq 5)` | `if ((Get-Item $x) -and ($y -eq 5))` |

**Rule:** Each cmdlet call MUST be in parentheses when using logical operators.

---

## 2. Unicode/Emoji Restriction

### CRITICAL: No Unicode in Scripts

| Purpose | ❌ Don't Use | ✅ Use |
|---------|-------------|--------|
| Success | ✅ ✓ | [OK] [+] |
| Error | ❌ ✗ 🔴 | [!] [X] |
| Warning | ⚠️ 🟡 | [*] [WARN] |
| Info | ℹ️ 🔵 | [i] [INFO] |
| Progress | ⏳ | [...] |

**Rule:** Use ASCII characters only in PowerShell scripts.

---

## 3. Null Check Patterns

### Always Check Before Access

| ❌ Wrong | ✅ Correct |
|----------|-----------|
| `$array.Count -gt 0` | `$array -and $array.Count -gt 0` |
| `$text.Length` | `if ($text) { $text.Length }` |

---

## 4. String Interpolation

### Complex Expressions

| ❌ Wrong | ✅ Correct |
|----------|-----------|
| `"Value: $($obj.prop.sub)"` | Store in variable first |

**Pattern:**
```
$value = $obj.prop.sub
Write-Output "Value: $value"
```

---

## 5. Error Handling

### ErrorActionPreference

| Value | Use |
|-------|-----|
| Stop | Development (fail fast) |
| Continue | Production scripts |
| SilentlyContinue | When errors expected |

### Try/Catch Pattern

- Don't return inside try block
- Use finally for cleanup
- Return after try/catch

---

## 6. File Paths

### Windows Path Rules

| Pattern | Use |
|---------|-----|
| Literal path | `C:\Users\User\file.txt` |
| Variable path | `Join-Path $env:USERPROFILE "file.txt"` |
| Relative | `Join-Path $ScriptDir "data"` |

**Rule:** Use Join-Path for cross-platform safety.

---

## 7. Array Operations

### Correct Patterns

| Operation | Syntax |
|-----------|--------|
| Empty array | `$array = @()` |
| Add item | `$array += $item` |
| ArrayList add | `$list.Add($item) | Out-Null` |

---

## 8. JSON Operations

### CRITICAL: Depth Parameter

| ❌ Wrong | ✅ Correct |
|----------|-----------|
| `ConvertTo-Json` | `ConvertTo-Json -Depth 10` |

**Rule:** Always specify `-Depth` for nested objects.

### File Operations

| Operation | Pattern |
|-----------|---------|
| Read | `Get-Content "file.json" -Raw | ConvertFrom-Json` |
| Write | `$data | ConvertTo-Json -Depth 10 | Out-File "file.json" -Encoding UTF8` |

---

## 9. Common Errors

| Error Message | Cause | Fix |
|---------------|-------|-----|
| "parameter 'or'" | Missing parentheses | Wrap cmdlets in () |
| "Unexpected token" | Unicode character | Use ASCII only |
| "Cannot find property" | Null object | Check null first |
| "Cannot convert" | Type mismatch | Use .ToString() |

---

## 10. Script Template

```powershell
# Strict mode
Set-StrictMode -Version Latest
$ErrorActionPreference = "Continue"

# Paths
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path

# Main
try {
    # Logic here
    Write-Output "[OK] Done"
    exit 0
}
catch {
    Write-Warning "Error: $_"
    exit 1
}
```

---

> **Remember:** PowerShell has unique syntax rules. Parentheses, ASCII-only, and null checks are non-negotiable.

Overview

This skill documents essential PowerShell Windows patterns focused on operator syntax, error handling, null checks, and common pitfalls. It condenses rules that prevent frequent runtime errors and maintain script portability and reliability. Use it as a checklist when writing or reviewing PowerShell scripts for Windows environments.

How this skill works

The skill highlights critical syntax requirements (notably parentheses around cmdlet calls when using logical operators), enforces ASCII-only script content, and presents safe patterns for null checks, string interpolation, file and JSON operations, and array handling. It explains ErrorActionPreference and a recommended try/catch/finally flow, plus a minimal strict-mode script template for robust scripts. Follow the examples to avoid typical runtime errors and maintain consistent output formatting.

When to use it

  • When authoring new PowerShell scripts for Windows to avoid syntax and runtime errors
  • When refactoring scripts to be more robust and cross-platform safe (path handling)
  • During code review to check for null-safety, operator misuse, and Unicode issues
  • When handling JSON serialization/deserialization of nested objects
  • When standardizing error handling and exit behavior across scripts

Best practices

  • Wrap each cmdlet call in parentheses when using -and, -or, -not to avoid parser errors
  • Use ASCII characters only in code and message tokens to prevent unexpected tokens
  • Always check objects for null before accessing properties or Count
  • Use Join-Path for building paths and $ScriptDir for script-relative files
  • Specify -Depth with ConvertTo-Json for nested objects and use -Raw with Get-Content

Example use cases

  • A deployment script that must reliably test multiple paths with logical operators
  • A logging utility that needs ASCII-only status tokens for downstream parsers
  • Reading and writing deeply nested configuration objects as JSON with -Depth
  • A module that needs strict null checks before property access to avoid exceptions
  • A maintenance script using Try/Catch/Finally with consistent exit codes

FAQ

Why must cmdlet calls be parenthesized with logical operators?

PowerShell parses logical operators at a different precedence; wrapping each cmdlet call in () ensures the call executes and its boolean result is evaluated correctly.

When should I use ErrorActionPreference = 'Stop'?

Use 'Stop' during development or testing to fail fast and catch issues; use 'Continue' in production scripts unless you expect specific recoverable errors.