脚本与函数
.ps1、param、execution policy。
35 分钟
脚本与函数
.ps1 是 PowerShell 脚本文件;param() 块声明参数,function 封装可复用逻辑。本站 deploy\scripts\sync-courses.ps1 是标准范例:参数化、错误处理、try/finally。
学习目标
- 编写带
param()的.ps1脚本 - 理解执行策略(Execution Policy)
- 掌握
$ErrorActionPreference与try/catch/finally
核心内容
最小脚本
# check-health.ps1
param(
[string]$ApiBase = "http://127.0.0.1:8080"
)
$ErrorActionPreference = "Stop"
Invoke-RestMethod "$ApiBase/actuator/health"
Write-Host "[OK] backend healthy"
运行:.\check-health.ps1 或 .\check-health.ps1 -ApiBase "http://localhost:8080"。
执行策略
Get-ExecutionPolicy -List
Set-ExecutionPolicy -Scope CurrentUser RemoteSigned
Restricted 阻止本地脚本;开发机常用 RemoteSigned(本地脚本可跑,下载的需签名)。GHA runner 默认较宽松(见 ps-gha)。
对照 sync-courses.ps1
param(
[string]$ApiBase = "http://127.0.0.1:8080",
[switch]$DryRun,
[switch]$SkipImport
)
$Root = Resolve-Path (Join-Path $PSScriptRoot "..\..")
Push-Location $Root
try {
$env:API_BASE = $ApiBase
node scripts/import-all-courses.mjs
if ($LASTEXITCODE -ne 0) { throw "import failed" }
} finally {
Pop-Location
Remove-Item Env:API_BASE -ErrorAction SilentlyContinue
}
要点:$PSScriptRoot 定位脚本目录;$LASTEXITCODE 检查外部命令(node/npm);finally 保证清理环境变量。
函数
function Test-PortListening { param([int]$Port)
[bool](Get-NetTCPConnection -LocalPort $Port -State Listen -EA SilentlyContinue)
}
函数名用 Verb-Noun;输出即返回值。
练习
- 写
check-health.ps1,接受-ApiBase参数 - 查看当前 ExecutionPolicy,必要时设为 RemoteSigned
- 阅读 的 与 块