powershell-windows

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

PowerShell Windows Patterns

Windows环境下的PowerShell使用模式

Critical patterns and pitfalls for Windows PowerShell.

Windows PowerShell的关键使用模式与常见陷阱。

1. Operator Syntax Rules

1. 运算符语法规则

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.

❌ 错误写法✅ 正确写法
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 Restriction

2. Unicode/表情符号限制

CRITICAL: No Unicode in Scripts

重点:脚本中禁止使用Unicode

Purpose❌ Don't Use✅ Use
Success✅ ✓[OK] [+]
Error❌ ✗ 🔴[!] [X]
Warning⚠️ 🟡[*] [WARN]
Infoℹ️ 🔵[i] [INFO]
Progress[...]
Rule: Use ASCII characters only in PowerShell scripts.

用途❌ 禁止使用✅ 推荐使用
成功✅ ✓[OK] [+]
错误❌ ✗ 🔴[!] [X]
警告⚠️ 🟡[*] [WARN]
信息ℹ️ 🔵[i] [INFO]
进度[...]
规则: PowerShell脚本中仅使用ASCII字符。

3. Null Check Patterns

3. 空值检查模式

Always Check Before Access

访问前务必检查

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

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

4. String Interpolation

4. 字符串插值

Complex Expressions

复杂表达式

❌ Wrong✅ Correct
"Value: $($obj.prop.sub)"
Store in variable first
Pattern:
$value = $obj.prop.sub
Write-Output "Value: $value"

❌ 错误写法✅ 正确写法
"Value: $($obj.prop.sub)"
先存储到变量中
模式:
$value = $obj.prop.sub
Write-Output "Value: $value"

5. Error Handling

5. 错误处理

ErrorActionPreference

ErrorActionPreference设置

ValueUse
StopDevelopment (fail fast)
ContinueProduction scripts
SilentlyContinueWhen errors expected
取值适用场景
Stop开发环境(快速失败)
Continue生产环境脚本
SilentlyContinue预期会出现错误的场景

Try/Catch Pattern

Try/Catch 模式

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

  • 不要在try块内返回结果
  • 使用finally块进行清理操作
  • 在try/catch之后返回结果

6. File Paths

6. 文件路径

Windows Path Rules

Windows路径规则

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

模式适用场景
字面路径
C:\Users\User\file.txt
变量路径
Join-Path $env:USERPROFILE "file.txt"
相对路径
Join-Path $ScriptDir "data"
规则: 为了跨平台兼容性,使用Join-Path命令。

7. Array Operations

7. 数组操作

Correct Patterns

正确操作模式

OperationSyntax
Empty array
$array = @()
Add item
$array += $item
ArrayList add`$list.Add($item)

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

8. JSON Operations

8. JSON操作

CRITICAL: Depth Parameter

重点:Depth参数

❌ Wrong✅ Correct
ConvertTo-Json
ConvertTo-Json -Depth 10
Rule: Always specify
-Depth
for nested objects.
❌ 错误写法✅ 正确写法
ConvertTo-Json
ConvertTo-Json -Depth 10
规则: 处理嵌套对象时务必指定
-Depth
参数。

File Operations

文件操作

OperationPattern
Read`Get-Content "file.json" -Raw
Write`$data

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

9. Common Errors

9. 常见错误

Error MessageCauseFix
"parameter 'or'"Missing parenthesesWrap cmdlets in ()
"Unexpected token"Unicode characterUse ASCII only
"Cannot find property"Null objectCheck null first
"Cannot convert"Type mismatchUse .ToString()

错误信息原因解决方法
"parameter 'or'"缺少括号用()包裹cmdlet
"Unexpected token"包含Unicode字符仅使用ASCII字符
"Cannot find property"对象为空先检查空值
"Cannot convert"类型不匹配使用.ToString()方法

10. Script Template

10. 脚本模板

powershell
undefined
powershell
undefined

Strict mode

Strict mode

Set-StrictMode -Version Latest $ErrorActionPreference = "Continue"
Set-StrictMode -Version Latest $ErrorActionPreference = "Continue"

Paths

Paths

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

Main

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.
try { # Logic here Write-Output "[OK] Done" exit 0 } catch { Write-Warning "Error: $_" exit 1 }

---

> **注意:** PowerShell具有独特的语法规则。括号使用、仅ASCII字符、空值检查是必须遵守的要求。