mcpField
P
powershell-windows

powershell-windows

github.com/vudovn开发8.2k361 次安装9 周前更新
代码仓库

关于 powershell-windows

面向脚本作者的 Windows PowerShell 模式技能,汇总语法规则与常见问题,涵盖逻辑运算符括号、仅使用 ASCII、空值检查、错误处理、路径、数组和 JSON。

主要功能

  1. 01逻辑运算符括号规则
  2. 02仅使用 ASCII 的脚本规范
  3. 03空值检查与插值模式
  4. 04错误处理与路径实践
  5. 05数组和 JSON 操作

适用场景

  1. 01避免 PowerShell 解析错误
  2. 02编写可处理空值的脚本
  3. 03为脚本选择错误处理方式
  4. 04读写嵌套 JSON

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/vudovn/ag-kit --skill powershell-windows

安装后在 Claude Code 中输入/powershell-windows确认已加载。

详细介绍

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/表情符号限制

关键:脚本中不要使用 Unicode
用途❌ 不要使用✅ 使用
成功✅ ✓[OK] [+]
错误❌ ✗ 🔴[!] [X]
警告⚠️ 🟡[*] [WARN]
信息ℹ️ 🔵[i] [INFO]
进度⏳[...]

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


3. Null 检查模式

访问前务必检查
❌ 错误✅ 正确
$array.Count -gt 0$array -and $array.Count -gt 0
$text.Lengthif ($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) | Out-Null

8. JSON 操作

关键:Depth 参数
❌ 错误✅ 正确
ConvertTo-JsonConvertTo-Json -Depth 10

规则: 对嵌套对象始终指定 -Depth。

文件操作
操作模式
读取Get-Content "file.json" -Raw | ConvertFrom-Json
写入$data | ConvertTo-Json -Depth 10 | Out-File "file.json" -Encoding UTF8

9. 常见错误

错误消息原因修复方法
"parameter 'or'"缺少括号将 cmdlet 用 () 括起来
"Unexpected token"Unicode 字符仅使用 ASCII
"Cannot find property"Null 对象先检查 null
"Cannot convert"类型不匹配使用 .ToString()

10. 脚本模板

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

记住: PowerShell 有独特的语法规则。括号、仅用 ASCII 字符和 null 检查都是不可妥协的要求。

评论

支持 Markdown