- name
- powershell-patterns
- description
- Idiomatic PowerShell patterns for Windows automation with proper error handling, splatting, pipeline idioms, and safety practices. Integrates PowerShell Windows Patterns skill and PowerSkills primitives.
- version
- 1.0.0
- sources
- ["https://github.com/athility/krashitos-ai-os-portfolio/blob/main/skills/powershell-windows/SKILL.md","https://github.com/aloth/PowerSkills"]
# PowerShell Patterns Skill
## 核心原則
1. **始終用 `-ErrorAction Stop`** — 確保錯誤進入 catch
2. **`try/catch/finally` 包裹** — 不要讓例外靜默失敗
3. **使用 Splatting** — 長參數清單用 `@params` 展開
4. **`-WhatIf` 優先** — 破壞性操作先預覽
5. **避免 `Invoke-Expression`** — 命令注入風險
## 錯誤處理模板
```powershell
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory)]
[string]$Path
)
try {
$item = Get-Item -Path $Path -ErrorAction Stop
if ($PSCmdlet.ShouldProcess($Path, "Remove")) {
Remove-Item -Path $item.FullName -ErrorAction Stop
Write-Output "已刪除:$($item.FullName)"
}
}
catch [System.IO.FileNotFoundException] {
Write-Error "找不到檔案:$Path"
}
catch {
Write-Error "未預期的錯誤:$($_.Exception.Message)"
}
finally {
# 清理資源(連線、COM 物件等)
}
```
## Splatting 模式
```powershell
# 不好:難以閱讀
Copy-Item -Path "C:\source\file.txt" -Destination "D:\backup\file.txt" -Force -Recurse
# 好:清晰、可維護
$copyParams = @{
Path = "C:\source\file.txt"
Destination = "D:\backup\file.txt"
Force = $true
Recurse = $true
}
Copy-Item @copyParams
```
## 常用操作模式
### 檔案系統
```powershell
# 安全地建立目錄
$dir = "C:\Users\eda\myapp"
if (-not (Test-Path $dir)) {
New-Item -ItemType Directory -Path $dir -Force | Out-Null
}
# 取得大型檔案(含錯誤處理)
Get-ChildItem -Path $dir -Recurse -ErrorAction SilentlyContinue |
Where-Object { $_.Length -gt 100MB } |
Sort-Object Length -Descending |
Select-Object Name, @{N='Size(MB)';E={[math]::Round($_.Length/1MB,2)}}
```
### 服務管理
```powershell
# 安全重啟服務(先 WhatIf)
function Restart-ServiceSafe {
param([string]$Name)
$svc = Get-Service -Name $Name -ErrorAction Stop
Write-Host "目前狀態:$($svc.Status)"
Restart-Service -Name $Name -WhatIf
$confirm = Read-Host "確認重啟 $Name?(y/N)"
if ($confirm -eq 'y') {
Restart-Service -Name $Name -ErrorAction Stop
}
}
```
### 進程管理
```powershell
# 列出佔用 CPU 最高的進程
Get-Process |
Sort-Object CPU -Descending |
Select-Object -First 10 Name, CPU, WorkingSet |
Format-Table -AutoSize
```
## PowerSkills 整合(`engines/powerskills/`)
```powershell
# 匯入 PowerSkills 模組
Import-Module "$PSScriptRoot\..\..\engines\powerskills\PowerSkills.psd1"
# 使用封裝好的工具
Invoke-PSFileOperation -Path "C:\data" -Operation Backup
Invoke-PSRegistryOperation -Key "HKCU:\Software\MyApp" -Action Export
```
## 參考資料
- `references/error-handling.md` — 詳細錯誤處理模式
- `references/splatting.md` — 參數展開技巧
- `references/pipeline-idioms.md` — Pipeline 慣用寫法
- `references/remoting.md` — 遠端執行模式
- `examples/file-ops.ps1` — 檔案操作範例
- `examples/registry-ops.ps1` — 登錄檔範例
- `examples/service-mgmt.ps1` — 服務管理範例
View on GitHub