PowerShellWindows模式Skill powershell-windows

这个技能提供了在Windows环境下使用PowerShell的关键模式、语法规则和错误处理方法,帮助开发者编写高效、稳定的自动化脚本。关键词:PowerShell, Windows, 脚本编写, 错误处理, 自动化, 模式, 语法规则, 错误处理模式。

DevOps 0 次安装 0 次浏览 更新于 3/21/2026

名称: powershell-windows 描述: PowerShell Windows 模式。关键陷阱、运算符语法、错误处理。 允许工具: 读取、写入、编辑、全局、grep、Bash

PowerShell Windows 模式

Windows PowerShell 的关键模式和陷阱。


1. 运算符语法规则

关键:必须使用括号

❌ 错误 ✅ 正确
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))

规则: 使用逻辑运算符时,每个 cmdlet 调用必须在括号中。


2. Unicode/Emoji 限制

关键:脚本中不要使用 Unicode

目的 ❌ 不要使用 ✅ 使用
成功 ✅ ✓ [OK] [+]
错误 ❌ ✗ 🔴 [!] [X]
警告 ⚠️ 🟡 [*] [WARN]
信息 ℹ️ 🔵 [i] [INFO]
进度 […]

规则: 在 PowerShell 脚本中只使用 ASCII 字符。


3. 空值检查模式

访问前总是检查

❌ 错误 ✅ 正确
$array.Count -gt 0 $array -and $array.Count -gt 0
$text.Length if ($text) { $text.Length }

4. 字符串插值

复杂表达式

❌ 错误 ✅ 正确
"Value: $($obj.prop.sub)" 先存储在变量中

模式:

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

5. 错误处理

ErrorActionPreference

使用场景
Stop 开发(快速失败)
Continue 生产脚本
SilentlyContinue 当预期有错误时

Try/Catch 模式

  • 不要在 try 块中返回
  • 使用 finally 进行清理
  • 在 try/catch 后返回

6. 文件路径

Windows 路径规则

模式 使用
字面路径 C:\Users\User\file.txt
变量路径 Join-Path $env:USERPROFILE "file.txt"
相对路径 Join-Path $ScriptDir "data"

规则: 使用 Join-Path 以确保跨平台安全。


7. 数组操作

正确模式

操作 语法
空数组 $array = @()
添加项 $array += $item
ArrayList 添加 `$list.Add($item)

8. JSON 操作

关键:深度参数

❌ 错误 ✅ 正确
ConvertTo-Json ConvertTo-Json -Depth 10

规则: 对于嵌套对象,总是指定 -Depth

文件操作

操作 模式
读取 `Get-Content “file.json” -Raw
写入 `$data

9. 常见错误

错误消息 原因 修复
“parameter ‘or’” 缺少括号 将 cmdlet 包装在 () 中
“Unexpected token” Unicode 字符 只使用 ASCII
“Cannot find property” 空对象 先检查空值
“Cannot convert” 类型不匹配 使用 .ToString()

10. 脚本模板

# 严格模式
Set-StrictMode -Version Latest
$ErrorActionPreference = "Continue"

# 路径
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path

# 主逻辑
try {
    # 逻辑在这里
    Write-Output "[OK] 完成"
    exit 0
}
catch {
    Write-Warning "错误:$_"
    exit 1
}

记住: PowerShell 有独特的语法规则。括号、仅 ASCII 和空值检查是不可协商的。