Skip to content

Commit 7dd8d60

Browse files
committed
docs(cheatsheet): 添加跨平台PowerShell脚本模板
添加一个标准的PowerShell脚本模板,包含高级函数特性、错误处理、跨平台支持和示例说明
1 parent 1b8c414 commit 7dd8d60

1 file changed

Lines changed: 103 additions & 0 deletions

File tree

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
#!/usr/bin/env pwsh
2+
3+
<#
4+
.SYNOPSIS
5+
脚本简短摘要(例如:跨平台自动化部署脚本)。
6+
7+
.DESCRIPTION
8+
详细描述脚本的功能。此处可以写多行。
9+
该脚本演示了编写跨平台 PowerShell 的标准结构。
10+
11+
.PARAMETER TargetPath
12+
目标路径参数说明。默认值为当前路径。
13+
14+
.PARAMETER Force
15+
开关参数。如果指定,将强制执行操作。
16+
17+
.EXAMPLE
18+
# Linux/macOS
19+
./script-template.ps1 -TargetPath "/tmp/output" -Verbose
20+
21+
.EXAMPLE
22+
# Windows
23+
.\script-template.ps1 -TargetPath "C:\Temp" -Force
24+
#>
25+
26+
# 1. 启用高级函数特性 (支持 -Verbose, -Debug, -WhatIf 等)
27+
[CmdletBinding(SupportsShouldProcess = $true)]
28+
param(
29+
[Parameter(Mandatory = $false, HelpMessage = "指定目标处理目录")]
30+
[string]$TargetPath = $PWD,
31+
32+
[Parameter(Mandatory = $false)]
33+
[switch]$Force
34+
)
35+
36+
# 2. 设置严格的错误处理模式
37+
# Latest: 禁止使用未初始化的变量,禁止调用不存在的属性
38+
Set-StrictMode -Version Latest
39+
# Stop: 遇到任何错误立即停止脚本执行
40+
$ErrorActionPreference = 'Stop'
41+
42+
# 3. 定义主逻辑函数 (保持全局作用域整洁)
43+
function Main {
44+
try {
45+
Write-Verbose "脚本启动..."
46+
47+
# --- 跨平台路径处理 ---
48+
# 始终使用 Join-Path,不要手动拼接 "/" 或 "\"
49+
$ConfigFile = Join-Path $PSScriptRoot "config" "settings.json"
50+
51+
# 规范化用户输入的路径
52+
$ResolvedPath = $TargetPath
53+
if (Test-Path $TargetPath) {
54+
$ResolvedPath = Convert-Path $TargetPath
55+
}
56+
Write-Verbose "目标路径: $ResolvedPath"
57+
Write-Verbose "配置文件路径 (预期): $ConfigFile"
58+
59+
# --- 操作系统检测逻辑 ---
60+
if ($IsLinux) {
61+
Write-Verbose "检测到操作系统: Linux"
62+
# Linux 特有逻辑...
63+
}
64+
elseif ($IsMacOS) {
65+
Write-Verbose "检测到操作系统: macOS"
66+
# macOS 特有逻辑...
67+
}
68+
elseif ($IsWindows) {
69+
Write-Verbose "检测到操作系统: Windows"
70+
# Windows 特有逻辑...
71+
}
72+
73+
# --- 核心业务逻辑示例 ---
74+
# 使用 SupportsShouldProcess 实现 -WhatIf 支持
75+
if ($PSCmdlet.ShouldProcess($ResolvedPath, "执行清理操作")) {
76+
77+
# 模拟操作
78+
if ($Force) {
79+
Write-Host "正在强制处理 [$ResolvedPath] ..." -ForegroundColor Yellow
80+
}
81+
else {
82+
Write-Host "正在正常处理 [$ResolvedPath] ..." -ForegroundColor Cyan
83+
}
84+
85+
# 模拟工作负载
86+
Start-Sleep -Milliseconds 500
87+
88+
Write-Host "操作完成。" -ForegroundColor Green
89+
}
90+
}
91+
catch {
92+
# 捕获并美化错误输出
93+
Write-Error "发生严重错误: $($_.Exception.Message)"
94+
# 返回非零状态码,便于 CI/CD 管道检测失败
95+
exit 1
96+
}
97+
finally {
98+
Write-Verbose "脚本执行结束 (清理资源...)"
99+
}
100+
}
101+
102+
# 4. 执行主函数
103+
Main

0 commit comments

Comments
 (0)