技能 编程开发 PowerShell最佳实践与语法指南

PowerShell最佳实践与语法指南

v20260424
powershell-windows
本指南详细介绍了在Windows环境下编写健壮PowerShell脚本的最佳实践和陷阱。内容涵盖了运算符语法、空值检查、错误处理(Try/Catch)、路径构建以及JSON操作等核心知识点,旨在帮助用户编写出高度可靠和可维护的自动化脚本。
获取技能
352 次下载
概览

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)

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
Write `$data

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

# 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.

When to Use

This skill is applicable to execute the workflow or actions described in the overview.

Limitations

  • Use this skill only when the task clearly matches the scope described above.
  • Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
  • Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.
信息
Category 编程开发
Name powershell-windows
版本 v20260424
大小 3.84KB
更新时间 2026-04-25
语言