powershell-windows
/powershell-windows
PowerShell pitfalls on Windows - operators, quoting, encoding, paths, errors; use when writing or running PowerShell.
- Author
- Reprograme ↗
- Repository
- redevkit ↗
- Licence
- MIT
- Last repository change
- 12.11.2026
Assessment and security
- Files in this package
- 1
- Scripts
- 0
- HTML comments
- 0
- URLs in SKILL.md
- 0
No signals detected. Repository changed on 12.11.2026, without references to retired models or APIs.
MIT, open: use and modify while retaining author attribution.
What it does and when to use it
PowerShell pitfalls on Windows - operators, quoting, encoding, paths, errors; use when writing or running PowerShell.
Original author description
PowerShell pitfalls on Windows - operators, quoting, encoding, paths, errors; use when writing or running PowerShell.
How it works
- 1. Operator Syntax Rules
- 2. Encoding and Unicode
- 3. Null Check Patterns
- 4. String Interpolation
- 5. Error Handling
- 6. File Paths
- 7. Array Operations
- 8. JSON Operations
- 9. Chaining and Redirection
- 10. Common Errors
SKILL.md preview
---
name: powershell-windows
description: PowerShell pitfalls on Windows - operators, quoting, encoding, paths, errors; use when writing or running PowerShell.
---
# PowerShell Windows Patterns
> Critical patterns and pitfalls for Windows PowerShell 5.1 and PowerShell 7+ (`pwsh`).
> Check the version first: `$PSVersionTable.PSVersion`.
---
## 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. Encoding and Unicode
### Encoding: Always UTF-8 When Writing Files
Files are UTF-8. Prefer the file-editing tool over shell writes. When a shell write is
unavoidable, pass `-Encoding` on every write:
| ❌ Don't | ✅ Do |
|----------|-------|
| `Get-Content f` (5.1 reads BOM-less UTF-8 as ANSI) | `Get-Content f -Raw -Encoding UTF8` |
| `Set-Content f $text` | `Set-Content f $text -NoNewline -Encoding utf8` (PowerShell 7: `utf8NoBOM`) |
| `cmd > f`, `Out-File f` on Windows PowerShell 5.1 (UTF-16 LE) | `cmd \| Set-Content f -Encoding utf8` or `Out-File f -Encoding utf8` |
| `Add-Content f $line` | `Add-Content f $line -Encoding utf8` |
In Windows PowerShell 5.1, `-Encoding UTF8` writes a BOM; PowerShell 7 defaults to UTF-8
without BOM and accepts `utf8NoBOM`. Check accents after a write.
### CRITICAL: Prefer ASCII in Scripts
Windows PowerShell 5.1 reads a UTF-8 script **without BOM** as the ANSI code page, so emoji
and accented characters break parsing or output. PowerShell 7 reads UTF-8 correctly. Keep
scripts ASCII, or save them as UTF-8 with BOM when 5.1 must run them.
| Purpose | ❌ Don't Use | ✅ Use |
|---------|-------------|--------|
| Success | ✅ ✓ | [OK] [+] |
| Error | ❌ ✗ 🔴 | [!] [X] |
| Warning | ⚠️ 🟡 | [*] [WARN] |
| Info | ℹ️ 🔵 | [i] [INFO] |
| Progress | ⏳ | [...] |
**Rule:** Use ASCII status markers in scripts that may run on Windows PowerShell 5.1.
---
## 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
### Property Access Needs a Subexpression
| ❌ Wrong | ✅ Correct |
|----------|-----------|
| `"Value: $obj.prop"` (expands only `$obj`) | `"Value: $($obj.prop)"` |
For long expressions, store the value in a variable first:
```powershell
$value = $obj.prop.sub
Write-Output "Value: $value"
```
Single quotes never expand: `'Cost: $5'` stays literal.
---
## 5. Error Handling
### ErrorActionPreference
| Value | Use |
|-------|-----|
| Stop | Development and scripts that must fail fast |
| Continue | Scripts that log and keep going |
| SilentlyContinue | When errors are expected and handled |
### Try/Catch Pattern
- `try/catch` only catches terminating errors; add `-ErrorAction Stop` to the cmdlet
- Use `finally` for cleanup
- Prefer returning after the `try/catch` block
- A failing native command (`git`, `npm`) does not throw; check `$LASTEXITCODE`
---
## 6. File Paths
### Windows Path Rules
| Pattern | Use |
|---------|-----|
| Literal path | `C:\Users\User\file.txt` |
| Variable path | `Join-Path $env:USERPROFILE "file.txt"` |
| Relative to script | `Join-Path $PSScriptRoot "data"` |
| Path with spaces | Always quote: `"C:\Program Files\App"` |
**Rule:** Use `Join-Path` instead of string concatenation.
---
## 7. Array Operations
### Correct Patterns
| Operation | Syntax |
|-----------|--------|
| Empty array | `$array = @()` |
| Add item (small arrays) | `$array += $item` |
| Many items | `$list = [System.Collections.Generic.List[object]]::new(); $list.Add($item)` |
| Force array result | `@(Get-ChildItem *.log)` |
---
## 8. JSON Operations
### CRITICAL: Depth Parameter
| ❌ Wrong | ✅ Correct |
|----------|-----------|
| `ConvertTo-Json` | `ConvertTo-Json -Depth 10` |
**Rule:** Always specify `-Depth` for nested objects (the default is 2 and silently truncates).
### File Operations
| Operation | Pattern |
|-----------|---------|
| Read | `Get-Content "file.json" -Raw \| ConvertFrom-Json` |
| Write | `$data \| ConvertTo-Json -Depth 10 \| Set-Content "file.json" -Encoding UTF8` |
---
## 9. Chaining and Redirection
| Need | Windows PowerShell 5.1 | PowerShell 7+ |
|------|------------------------|---------------|
| Run B only if A succeeds | `A; if ($?) { B }` | `A && B` |
| Discard errors | `2>$null` | `2>$null` |
| Set an environment variable | `$env:NAME = "x"` | same |
| Run an exe whose path has spaces | `& "C:\Program Files\App\app.exe" arg` | same |
Bash syntax (`export`, `VAR=x cmd`, `[ -f x ]`, backticks for substitution) does not work.
---
## 10. Common Errors
| Error Message | Cause | Fix |
|---------------|-------|-----|
| "parameter 'or'" | Missing parentheses | Wrap cmdlets in () |
| "Unexpected token" | Non-ASCII character in a 5.1 script | Use ASCII or UTF-8 with BOM |
| "Cannot find property" | Null object | Check null first |
| "Cannot convert" | Type mismatch | Use .ToString() or a cast |
| "is not recognized as the name of a cmdlet" | Bash command or missing exe | Use the PowerShell equivalent |
---
## 11. Script Template
```powershell
# Strict mode
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
# Paths
$ScriptDir = $PSScriptRoot
# Main
try {
# Logic here
Write-Output "[OK] Done"
exit 0
}
catch {
Write-Warning "Error: $_"
exit 1
}
```
---
> **Remember:** PowerShell has unique syntax rules. Parentheses, encoding and null checks are
> non-negotiable.
Versions
| Repository | Score | Licence |
|---|---|---|
| This page · Reprograme/redevkit | 98 | MIT |
| jeffersonvalente/cardume | 98 | MIT |
Database snapshot: 13.11.2026 · package version 3821a2e4dd69 (SHA-256 digest of the entire package)
Downloads in the last 30 days: 0 · ranking
Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.
Similar skills
- 100windows-agent-shell
A coding agent on Windows: Git Bash path rewriting, PowerShell quoting and encoding, CRLF. Use when output comes back garbled, or it works here and breaks there. - 96powershell
PowerShell开发专家助手。当用户需要进行PowerShell脚本开发、Windows自动化、系统运维脚本、模块开发或跨平台管理任务时调用。 - 90powershell
在 Windows PowerShell 7 中写可靠的命令和 .ps1 脚本,避开从 bash/Linux 迁移过来的陷阱:引号与参数传递、编码与行尾、JSON 深度、原生命令退出码、路径与字面量、别名差异。当需要在 Windows 上执行 shell 命令、编写或调试 PowerShell 脚本、或 bash 命令在 PowerShell 中行为不符预期时使用。 - 90windows-powershell-automation
Diagnose and automate Windows administration tasks with PowerShell. Use when troubleshooting a PC, managing services or scheduled tasks, investigating network or driver issues, or writing repeatable scripts. Inspect first and protect user data. - 98powershell-safe-invocation
Use when writing or running PowerShell on Windows, especially native programs, quoted paths, escaping, pwsh, Start-Process, file operations, or shell troubleshooting. - 98powershell-safe-invocation
Use when writing or running PowerShell on Windows, especially native programs, quoted paths, escaping, pwsh, Start-Process, file operations, or shell troubleshooting.