PowerShell 第 3 课:函数、作用域与高级函数
[CmdletBinding()] 如何带来通用参数和严格绑定、如何声明带类型、带校验、可补全的参数、如何正确接收管道输入、如何为输出写文档和类型 —— 最后完成 OpsKit 的前三个命令Get-Content,这些规则现在原样适用于你自己的函数,因为高级函数和编译好的 cmdlet 由同一个引擎绑定。OpsKit 里程碑:课程项目从这里起步,版本 v0.1——~/pslab/OpsKit 中的三个独立函数(Get-OpsServer、Get-OpsConfig、Test-OpsEndpoint),由一个点源加载脚本载入。第 4 课把它们打包成真正的模块。- 预测函数的输出:所有没有被捕获的值都会进入成功输出流(包括
ArrayList.Add返回的索引);return只负责退出;集合会被展开,除非使用逗号运算符或Write-Output -NoEnumerate。 - 解释动态作用域:子作用域可以读取父作用域的变量,赋值则会创建本地副本;
$script:/$global:/$private:改变这一规则;点源在调用方作用域中运行;$using:把值带进并行运行空间。 - 用
[CmdletBinding()]把函数变成高级函数,并用好它带来的能力:通用参数、Write-Verbose、$PSCmdlet、$PSBoundParameters,以及拒绝未知参数。 - 精确声明参数:类型、Mandatory、Position、默认值、
[switch]、别名,以及带DefaultParameterSetName的参数集。 - 用
Validate*特性(以及自定义ErrorMessage)在入口处校验输入,并通过ArgumentCompleter和Register-ArgumentCompleter提供 Tab 补全。 - 编写支持管道的函数:
ValueFromPipeline与ValueFromPipelineByPropertyName的区别、begin / process / end、[Alias('IP')]这样的别名——这是本课的核心动画——并用Trace-Command证明绑定过程。 - 让输出和用法可被发现:
[OutputType]、PSTypeName、放在正确位置的基于注释的帮助、展开传参与$PSBoundParameters转发,以及批准的动词。 - 构建并验证 OpsKit v0.1:让
Get-OpsServer -Env prod | Test-OpsEndpoint针对清单和本地 TCP 监听器端到端运行,并有验收检查和退出码。
1 小时时间分配
| # | 时间 | 模块 | 核心内容 | 动画 / 互动 | 实验(~/pslab) |
|---|---|---|---|---|---|
| 0 | 课前 | OpsKit 骨架 | ~/pslab/OpsKit:Public/、Private/、tests/ 和点源加载脚本 OpsKit.ps1;热身回顾第 1 课的 $args bug | 自检清单 | 创建骨架并加载一个测试函数 |
| 1 | 00–06 | 函数与输出 | function、param()、调用语法(f a b 而不是 f(a,b))、隐式输出、$null = / [void] / Out-Null、return、展开、, 与 -NoEnumerate | 输出收集器:什么进入了成功输出流 | 复现 ArrayList 索引泄漏并用三种方法修复 |
| 2 | 06–13 | 作用域 | global、script、local、private;读穿透与赋值即副本;Get-Variable -Scope;点源脚本与函数;$using:;闭包 | 作用域栈:这个变量住在哪里? | 复现“计数器没变”的 bug |
| 3 | 13–21 | 高级函数 | [CmdletBinding()]、12 个通用参数、Write-Verbose/-Verbose、-ErrorAction、$PSCmdlet、$PSBoundParameters、严格参数绑定 | 简单函数与高级函数:同一调用,两种结果 | 升级一个简单函数,看 -Nmae 明确报错 |
| 4 | 21–28 | 参数 | 类型与转换、Mandatory、AllowEmptyString、Position、默认值表达式、[switch]、参数集、DefaultParameterSetName、别名 | 参数集解析器 | 设计有三个参数集的 Get-Node |
| 5 | 28–35 | 校验与补全 | ValidateSet、ValidatePattern、ValidateRange、ValidateScript、ValidateNotNullOrEmpty、ValidateCount/Length、ErrorMessage、ArgumentCompleter、Register-ArgumentCompleter | 校验关卡:哪个特性拦下了这个值? | 用 TabExpansion2 验证补全器 |
| 6 | 35–42 | 管道输入 | ValueFromPipeline 与 ValueFromPipelineByPropertyName、begin / process / end、缺少 process 的 bug、[string[]] + foreach、[Alias('IP')]、类型转换陷阱 | 核心动画:绑定到你自己的函数 | 让 servers.csv 的行绑定到 -Target |
| 7 | 42–50 | 输出与帮助 | [OutputType]、PSTypeName 与 Update-TypeData、[PSTypeName()] 参数、帮助块位置、展开传参、$PSBoundParameters 转发、批准的动词 | 帮助块位置检查器 | 为 OpsKit 编写帮助;写一个转发包装函数 |
| 8 | 50–60 | OpsKit v0.1 | Get-OpsServer、Get-OpsConfig、Test-OpsEndpoint、加载脚本、本地 TcpListener | 端点测试演示 + 排错决策树 | 编写这三个函数 |
| — | 课后 | 速查表 · 综合实验 | 端到端使用 OpsKit:Get-OpsServer -Env prod | Test-OpsEndpoint;带退出码的验收脚本 Invoke-OpsKitCheck.ps1 | 结业测验(12 题) | 13 项检查全部通过 |
知识覆盖矩阵
| 目标技能 | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | 关键命令 | 实验 |
|---|---|---|---|---|---|---|---|---|---|---|
| 预测函数输出与展开 | ✓ | · | · | · | · | ✓ | ✓ | ✓ | $null =、[void]、return、,$a、-NoEnumerate | M1 |
| 理解作用域与点源 | · | ✓ | · | · | · | · | · | ✓ | $script:、$global:、$private:、. ./x.ps1、$using: | M2、M8 |
| 编写高级函数 | · | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | [CmdletBinding()]、$PSCmdlet、$PSBoundParameters | M3、综合实验 |
| 设计参数与参数集 | ✓ | · | ✓ | ✓ | ✓ | · | · | ✓ | [Parameter(Mandatory, Position, ParameterSetName)]、[switch]、[Alias()] | M4 |
| 校验与补全参数 | · | · | · | ✓ | ✓ | · | · | ✓ | [ValidateSet()]、[ValidateScript()]、Register-ArgumentCompleter、TabExpansion2 | M5、综合实验 |
| 正确接收管道输入 | · | · | · | · | · | ✓ | ✓ | ✓ | ValueFromPipeline(ByPropertyName)、process {}、Trace-Command | M6、综合实验 |
| 文档、类型与转发 | · | · | ✓ | · | · | · | ✓ | ✓ | [OutputType()]、PSTypeName、<# .SYNOPSIS #>、@params、Get-Verb | M7 |
| 构建并验证一个小工具包 | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | Import-PowerShellDataFile、TcpClient、TcpListener、退出码 | M8、综合实验 |
本课不包含的内容(以及去哪里学)
| 主题 | 为什么不在本课 | 去哪里学 |
|---|---|---|
脚本模块(.psm1)、模块清单、Export-ModuleMember、模块作用域、真正的私有函数、格式文件(.format.ps1xml)、发布 | 先有值得打包的函数,再谈打包 | 第 4 课:模块、包与提供程序(OpsKit v0.2) |
深入的 try/catch/finally、终止与非终止错误、$ErrorActionPreference、1–6 号输出流、SupportsShouldProcess / -WhatIf / -Confirm、Set-StrictMode | 本课只在函数确实需要时使用它们;安全变更是独立主题 | 第 5 课:健壮的脚本(OpsKit v0.3) |
ForEach-Object -Parallel、作业、运行空间、远程管理(本课只预览 $using:) | 并发与远程执行 | 第 6 课(OpsKit v0.4) |
PowerShell 类、枚举、DynamicParam | 工具函数很少需要;动态参数难以测试和发现 | 第 4 课会提到;参见 about_Classes、about_Functions_Advanced_Parameters |
| Pester 测试、PSScriptAnalyzer 规则、断点调试 | 质量工具;本课先用一个简单的验收脚本 | 第 8 课(OpsKit v1.0) |
如何使用本教材
原理 · 图解 · 动画 · 命令 · 实验 · 生产案例 · 排错 · 测验 · 语音 · 视频。先读“原理”和“动画”,再在
~/pslab 中做“实验”。模块 6 的管道输入动画延续第 1 课的绑定动画——只是接收方换成了你自己的函数。测验得分 ≥ 70%,或点击“标记本模块为已完成”,都会计入进度。进度保存在本浏览器的本地存储中(如果浏览器禁用了本地存储,刷新后会重置)。
“语音”分页使用浏览器内置的 Web Speech API(zh-CN)朗读讲解稿。没有中文语音包时仍可阅读讲解稿,或交给其他 TTS 工具。
ValidateScript/ValidatePattern 上的 ErrorMessage(PowerShell 6+)和 [ValidateNotNullOrWhiteSpace()](7.4+)。ProgressAction 在 7.4 中成为第 12 个通用参数。Windows PowerShell 5.1 的函数语言相同,但没有 ErrorMessage、空合并运算符和 ForEach-Object -Parallel。模块 8 的 TCP 结果取决于操作系统网络栈,Windows 特有的耗时已单独标注。模块 0 · 准备:OpsKit 项目骨架
~/pslab/OpsKit,包含 Public/、Private/、tests/,以及一个点源所有函数文件的小加载脚本 OpsKit.ps1——这就是 v0.1 的布局,第 4 课会把它变成真正的模块热身:凭记忆回答(30 秒)
1. 第 1 课综合实验中,New-Check 'envs' 'a,b' ('b','a' | Sort-Object) -join ',' 报告的是 a b 而不是 a,b。为什么多出来的 -join 和 ',' 没有引发任何报错?
New-Check 是一个简单函数(function New-Check([string]$Name, $Expected, $Actual))。在参数模式下,-join 只是一个看起来像参数名的单词;简单函数会把未知参数放进 $args 然后忽略。模块 3 会演示:加上 [CmdletBinding()] 之后,这个静默 bug 会立即变成明确的错误。
function New-Check([string]$Name, $Expected, $Actual) { "$Name expected=$Expected actual=$Actual" }
New-Check 'envs' 'a,b' ('b', 'a' | Sort-Object) -join ','
(Get-Command New-Check).CmdletBinding
envs expected=a,b actual=a b False
2. Get-Item ./data/servers.csv | Get-Content 能工作,'./data/servers.csv' | Get-Content 却失败。是哪条绑定规则?
FileInfo 按属性名(ByPropertyName)绑定:它的 PSPath 属性正好是 -LiteralPath 的别名。普通字符串没有这个属性,而 Get-Content 没有 ByValue 参数。本课你会给自己的参数加别名([Alias('IP')]),效果完全一样。
3. & ./lib.ps1 和 . ./lib.ps1 有什么区别?
调用运算符在一个新的脚本作用域里运行脚本,结束后作用域被丢弃;点源在调用方的作用域里运行,所以函数和变量会保留下来。OpsKit 加载脚本正依赖这一点(模块 2)。
第 1 步 —— 创建骨架
$kit = Join-Path $HOME 'pslab' 'OpsKit'
'Public', 'Private', 'tests' | ForEach-Object { New-Item -ItemType Directory -Path (Join-Path $kit $_) -Force } | Out-Null
Get-ChildItem $kit -Name
Private Public tests
| 路径 | v0.1(本课)中的内容 | 以后的变化 |
|---|---|---|
OpsKit/Public/ | 每个面向用户的函数一个文件:Get-OpsServer.ps1、Get-OpsConfig.ps1、Test-OpsEndpoint.ps1 | 第 4 课在模块清单中正好导出这些函数 |
OpsKit/Private/ | 辅助函数,例如 Get-OpsDataPath.ps1 | 第 4 课让它们真正私有(模块作用域);v0.1 中它们是可见的,因为一切都被点源进了你的会话 |
OpsKit/tests/ | Invoke-OpsKitCheck.ps1,一个普通的验收脚本(综合实验) | 第 8 课换成 Pester 6 测试和 CI |
OpsKit/OpsKit.ps1 | 加载脚本:先点源 Private/*.ps1,再点源 Public/*.ps1 | 第 4 课由 OpsKit.psd1 + OpsKit.psm1 取代 |
第 2 步 —— 加载脚本 OpsKit.ps1
把下面的内容保存为 ~/pslab/OpsKit/OpsKit.ps1。有两个细节很关键:foreach 语句不会创建作用域,所以 . $file.FullName 会把每个函数定义在加载脚本自己的作用域里;而因为是你点源了加载脚本,这个作用域就是你的会话。如果改用 & 运行,加载脚本一返回,函数就消失了(模块 2 会复现)。
# OpsKit v0.1 loader. Dot-source it to load every function into your session:
# . ~/pslab/OpsKit/OpsKit.ps1
# Running it with & or ./ loads the functions into a script scope that disappears
# when the loader ends (Module 2). Lesson 4 replaces this file with OpsKit.psd1 + OpsKit.psm1.
foreach ($folder in 'Private', 'Public') {
$dir = Join-Path $PSScriptRoot $folder
foreach ($file in Get-ChildItem -LiteralPath $dir -Filter *.ps1 -File) {
. $file.FullName
}
}
第 3 步 —— 用一个临时函数验证加载脚本
Set-Content ~/pslab/OpsKit/Public/Get-OpsHello.ps1 -Value 'function Get-OpsHello { "OpsKit loaded from $PSScriptRoot" }'
. ~/pslab/OpsKit/OpsKit.ps1
Get-OpsHello
Get-ChildItem ~/pslab/OpsKit -Recurse -File | ForEach-Object { $_.FullName.Substring($HOME.Length + 1) }
Remove-Item ~/pslab/OpsKit/Public/Get-OpsHello.ps1
OpsKit loaded from C:\Users\labadmin\pslab\OpsKit\Public pslab\OpsKit\OpsKit.ps1 pslab\OpsKit\Public\Get-OpsHello.ps1
注意函数内部 $PSScriptRoot 的含义:它是定义该函数的文件所在的文件夹(Public),既不是加载脚本的文件夹,也不是你的当前位置。第 4 课的模块相对路径就依赖这一点。
第 4 步 —— 检查函数将要读取的数据
(Get-Content ~/pslab/data/inventory.json -Raw | ConvertFrom-Json).Count (Import-PowerShellDataFile ~/pslab/data/opskit.config.psd1).Environments.Keys | Sort-Object
12 dev prod staging
环境自检清单
~/pslab 之下(OpsKit/、scripts/、tmp/)。模块 8 只在 127.0.0.1:18080 上打开一个 TCP 监听器——回环地址,网络上无法访问——并在同一步骤中停止;如果你机器上的 18080 端口已被占用,换成任意大于 1024 的空闲端口即可。清单中的 10.x 地址是虚构的:连接它们会超时,这是预期结果,没有危害。如需重来:Remove-Item -LiteralPath ~/pslab/OpsKit -Recurse -Force,然后重复第 1–2 步。课后请保留该文件夹——第 4–8 课都在它的基础上继续。模块 1 · 函数:定义、参数与输出语义
return 后面的值。掌握这一条规则,就能避免一整类“结果里为什么多了 0 1 2?”的 bug- 用
param()块定义函数,并按 PowerShell 的方式调用:Add-Two 1 2,绝不写Add-Two(1, 2)。 - 说出输出规则:任何没有赋值、没有转换为
[void]、没有重定向的表达式或命令结果都会进入成功输出流——包括ArrayList.Add()、StringBuilder.Append()等 .NET 方法的返回值。 - 只用
return来提前退出函数,用$null =、[void]或| Out-Null抑制不需要的输出(并知道哪种最慢)。 - 预测展开:空数组变成“什么都没有”(
$null),单元素数组变成标量,List[T]变成Object[];用,$x或Write-Output -NoEnumerate保持集合完整,用@( )保护调用方。
是什么:函数是有名字的脚本块
function Get-Greeting { param([string]$Name = 'world') "Hello, $Name" } 会在 Function: 驱动器中创建一个条目。调用它时,PowerShell 创建一个新的子作用域,把实参绑定到 param() 中的变量,执行函数体,并把每一个输出对象在产生时立即流式传给调用方。定义方式有两种,对简单函数来说等价:
| 写法 | 示例 | 适用于 |
|---|---|---|
| 内联参数列表 | function Add-Two($a, $b) { $a + $b } | 很小的辅助函数;无法添加 [CmdletBinding()] 等特性 |
param() 块 | function Add-Two { param([int]$A, [int]$B) $A + $B } | 其他所有情况——只有这种写法能变成高级函数(模块 3) |
调用语法是命令语法,不是方法语法:实参之间用空格分隔。Add-Two(1, 2) 只传了一个实参——数组 1, 2——给 $a,$b 为空。在 7.6 中这甚至不会报错,你只会得到一个奇怪的结果。
为什么:输出规则
PowerShell 没有唯一的“返回值”。函数的结果就是成功输出流:所有没有赋给变量、没有转换为 [void]、没有管道到 Out-Null、也没有重定向的值。其中也包括你并不想输出的值:
| 函数中的这一行 | 它悄悄输出了什么 | 修复 |
|---|---|---|
$list.Add('web-01')(ArrayList) | 新元素的索引:0、1、2… | $null = $list.Add(…),或改用 List[string](它的 Add() 返回 void) |
$sb.AppendLine('x') | StringBuilder 本身 | [void]$sb.AppendLine('x') |
New-Item -ItemType Directory … | 一个 DirectoryInfo 对象 | $null = New-Item … |
对 $PSBoundParameters 调用 $hash.Remove('k') | True | $null = … |
Write-Host 'checking' | 什么都没有——它写到宿主(信息流) | 用于提示信息是正确的;绝不要用它输出数据 |
怎么做:return、展开与保持集合
return 'x' 是“输出 'x',然后退出”的简写。在它之前输出的所有内容仍然是结果的一部分。函数输出一个集合时,管道会把它枚举(一次一个对象,第 1 课模块 5);调用方赋值时,PowerShell 再把流收集起来:没有输出 → $null(严格说是 AutomationNull),一个元素 → 该元素本身,多个 → Object[]。原来的集合类型(List[string]、ArrayList)就丢失了。
| 函数以此结尾 | $r = f 得到 | 如何保持集合 |
|---|---|---|
@() | $null | ,@(),或调用方写 @(f) |
@('web-01') | [string] 'web-01' | ,@('web-01') |
@('a','b') | Object[] | (本身已是数组) |
一个 List[string] | Object[] | Write-Output $list -NoEnumerate 或 ,$list |
何时:选择哪种约定
对于工具函数(例如 OpsKit),一次输出一个对象,让调用方自己收集——这样可以流式处理,也能配合 Select-Object -First。只有当调用方确实需要一个集合对象时(少见:例如返回一张查找表)才使用 -NoEnumerate/逗号。在调用方,只要需要 .Count 或下标在 0 个、1 个、多个结果时都可靠,就用 @( ) 包起来。
return 才产生输出”——所有未捕获的值都会输出;return 只是退出。② “f(1, 2) 传了两个实参”——它传了一个数组。③ “函数返回 List,调用方就拿到 List”——调用方拿到的是 Object[](或标量,或 $null)。④ “Write-Host 的内容是结果的一部分”——$x = f 捕获不到它。⑤ “Out-Null 是惯用写法”——它能用,但在紧密循环中 $null = 大约快一倍(见下方实测)。图解:什么会到达调用方
图解:输出时的展开
输出收集器:什么进入了成功输出流?
选择一个函数,逐行执行。绿色 = 输出到成功输出流,黄色 = 执行了但没有输出,红色 = 意外的输出或结果。所有结果均在 PowerShell 7.6.10 上复现。
命令参考
| 语法 | 用途 | 说明 |
|---|---|---|
function Verb-Noun { param(…) … } | 定义函数 | 保存在 Function:;Get-Command Verb-Noun 可以看到 |
Verb-Noun -Name x / Verb-Noun x | 调用函数 | 实参之间用空格,不用括号,不用逗号 |
$null = expr | 丢弃一个值 | 最快;可读性好 |
[void]expr | 丢弃一个值 | 只适用于表达式,不适用于命令 |
cmd | Out-Null | 丢弃管道输出 | 三者中最慢 |
return $x | 输出 $x 并退出 | 之前的输出仍保留 |
, $array / Write-Output $x -NoEnumerate | 把集合作为一个对象输出 | 很少需要 |
@(f) | 调用结果总是数组 | 调用方保证 .Count 可靠 |
Get-Item Function:\Verb-Noun、Remove-Item Function:\… | 查看 / 删除函数 | Function 提供程序(第 4 课) |
function Get-Greeting {
param([string]$Name = 'world')
"Hello, $Name"
}
Get-Greeting
Get-Greeting -Name ops
Get-Greeting ops
Get-Command Get-Greeting | Format-List Name, CommandType, Definition
Hello, world
Hello, ops
Hello, ops
Name : Get-Greeting
CommandType : Function
Definition :
param([string]$Name = 'world')
"Hello, $Name"
function Add-Two($a, $b) { $a + $b }
Add-Two 1 2
Add-Two(1, 2)
Add-Two(1, 2) | ForEach-Object { "item: [$_]" }
3 1 2 item: [1] item: [2] item: []
如何验证:第三个元素是 $null:$a 收到的是数组 1, 2,而 @(1,2) + $null 会追加一个空元素。常见错误:像调用 C# 方法一样调用函数,从 Python 或 JavaScript 转过来的人尤其常见。生产用法:函数一旦成为高级函数(模块 3),像 [int]$A 这样的类型化参数会以清晰的转换错误拒绝这个数组,而不是产生垃圾结果。
function Get-Names {
$list = [System.Collections.ArrayList]::new()
foreach ($n in 'web-01', 'api-01', 'db-01') { $list.Add($n) }
"found $($list.Count) names"
}
Get-Names
$r = Get-Names
$r.Count
$r[0].GetType().Name
0 1 2 found 3 names 4 Int32
function New-Report {
$sb = [System.Text.StringBuilder]::new()
$sb.AppendLine('# Report') # leaks the StringBuilder
[void]$sb.AppendLine('servers: 12')
$sb.ToString()
}
(New-Report).Count
New-Report | ForEach-Object { $_.GetType().Name }
2 StringBuilder String
$list = [System.Collections.ArrayList]::new()
'{0,-10} {1,6:N0} ms' -f '$null =', (Measure-Command { foreach ($i in 1..100000) { $null = $list.Add($i) } }).TotalMilliseconds
'{0,-10} {1,6:N0} ms' -f '[void]', (Measure-Command { foreach ($i in 1..100000) { [void]$list.Add($i) } }).TotalMilliseconds
'{0,-10} {1,6:N0} ms' -f '| Out-Null', (Measure-Command { foreach ($i in 1..100000) { $list.Add($i) | Out-Null } }).TotalMilliseconds
$null = 605 ms [void] 653 ms | Out-Null 1,202 ms
| Out-Null 的开销来自每次调用都要建立管道。只有在几万次迭代的循环中才有意义;在普通代码中,选择团队最容易读懂的写法——但要保持一致。
目标:复现每一种输出意外并修复。环境:~/pslab 中的 pwsh 7.6(VS Code 或终端)。费用:无。
Get-Names 并运行。然后用三种方法修复:
function Get-NamesFixed {
$list = [System.Collections.ArrayList]::new()
$null = $list.Add('web-01')
[void]$list.Add('api-01')
$list.Add('db-01') | Out-Null
"found $($list.Count) names"
}
Get-NamesFixed
found 3 names
第四种修复往往最好:$list = [System.Collections.Generic.List[string]]::new()——它的 Add() 不返回任何值。
return 不会丢弃之前的输出:
function Test-Return {
'one'
return 'two'
'three'
}
Test-Return
$x = Test-Return
$x.Count
one two 2
return 是惯用的守卫语句:
function Get-Env([string]$Name) {
if ($Name -notin 'dev', 'staging', 'prod') { Write-Warning "unknown env $Name"; return }
"env $Name ok"
}
Get-Env prod
Get-Env qa
$null -eq (Get-Env qa 3>$null)
env prod ok WARNING: unknown env qa True
function Get-Zero { @() }
function Get-One { @('web-01') }
function Get-Two { @('web-01', 'api-01') }
function Get-List { $l = [System.Collections.Generic.List[string]]::new(); $l.Add('a'); $l.Add('b'); $l }
$z = Get-Zero; $null -eq $z
(Get-One).GetType().Name
(Get-Two).GetType().Name
(Get-List).GetType().FullName
True String Object[] System.Object[]
-NoEnumerate),以及调用方的替代方案 @( ):
function Get-OneKept { , @('web-01') }
function Get-ListKept { $l = [System.Collections.Generic.List[string]]::new(); $l.Add('a'); Write-Output $l -NoEnumerate }
(Get-OneKept).GetType().Name
(Get-OneKept).Count
(Get-ListKept).GetType().Name
Get-ListKept | ForEach-Object { "pipeline got: $($_.GetType().Name) with $($_.Count) item(s)" }
@(Get-One).Count
@(Get-Zero).Count
Object[] 1 List`1 pipeline got: List`1 with 1 item(s) 1 0
function Get-Status {
Write-Host 'checking...'
Write-Output 'ok'
'also output'
}
$s = Get-Status
"captured: $($s -join ' | ')"
checking... captured: ok | also output
Remove-Item Function:\Get-Names, Function:\Get-NamesFixed,或直接打开一个新终端。案例 1:邮件报告开头先出现“0 1 2 3 … 117”
问题:一个夜间函数用 ArrayList.Add() 构建过期账号列表,最后 return $list。邮件正文开头是 118 个数字。根因:每次 Add() 都把索引写进了成功输出流;return 只是把列表追加在后面。修复:使用 List[pscustomobject](Add 返回 void),或 $null = $list.Add(…);更好的做法是直接逐个输出对象,而不是先建列表。预防:写一个测试检查每个输出对象的类型(第 8 课)。
案例 2:“只有恰好匹配一台 VM 时 .Count 才出错”
问题:$vms = Get-StaleVm; if ($vms.Count -gt 0) { … } 在 0 台和多台时都正常,但在脚本的另一个版本里,只有一台 VM 时 $vms[0].Name 返回的是某个字符串属性的第一个字符。根因:单个结果不会被包成数组;当这个单一对象是字符串时,下标取到的是字符。修复:在调用处写 $vms = @(Get-StaleVm)。PowerShell 3+ 给标量提供了值为 1 的 .Count,这会把问题掩盖到你使用下标为止。
案例 3:一个“返回”了没人要的 DirectoryInfo 的辅助函数
问题:function Get-LogPath { New-Item -ItemType Directory $dir -Force; Join-Path $dir 'run.log' }——调用方执行 Add-Content -Path (Get-LogPath) -Value …,得到 “Add-Content: Unable to write content because it is a directory: '…\tmp\logs'.” 根因:有两个输出:DirectoryInfo 和路径字符串。-Path 接受 string[],所以两者都被当成目标,而第一个是文件夹(在 7.6.10 上复现:(Get-LogPath).Count 为 2)。修复:$null = New-Item …。
常见错误与修复
函数在真正的结果前面多输出了数字 / 对象
原因:未捕获的方法返回值(ArrayList.Add、StringBuilder.Append、HashSet.Add → True/False),或 New-Item 之类的 cmdlet。
f | ForEach-Object { '{0}: {1}' -f $_.GetType().Name, $_ } # find the intruders
修复:在出问题的那一行前加 $null =。
Unable to write content because it is a directory / 路径参数收到了两个值
原因:作为实参传入的函数返回了不止一个对象(见案例 3),或者你用方法式 f(a, b) 调用了函数,传入的是数组。对于带类型的高级函数,同样的错误会更早地以 “Cannot convert 'System.Object[]' …” 失败。
修复:用 (f).Count 和 (f) | Get-Member 检查;用空格分隔实参调用。
只有一个结果时 .Count 或 [0] 的表现不同
原因:展开——单个结果是标量。
修复:调用方写 @(f);如果约定是“总是返回一个集合”,则在函数内写 , $result。
函数在屏幕上打印了文本,但 $x = f 是空的
原因:文本来自 Write-Host(或 Format-* 的输出被送到了宿主)。
修复:用裸值或 Write-Output 输出数据;提示信息用 Write-Verbose(模块 3)。
1. 编写 Get-Port,把 inventory.json 中的端口作为一个 List[int] 对象返回(不展开),并证明其类型。
function Get-Port {
$l = [System.Collections.Generic.List[int]]::new()
foreach ($s in (Get-Content ~/pslab/data/inventory.json -Raw | ConvertFrom-Json)) { $l.Add($s.Port) }
, $l
}
(Get-Port).GetType().Name # List`1
(Get-Port).Count # 122. 找出函数中哪一行泄漏了输出。
Set-PSDebug -Trace 1; $null = Get-Names; Set-PSDebug -Off # shows each line as it runs
Get-Names | ForEach-Object { $_.GetType().Name } | Group-Object -NoElement第二行通常就够了:3 Int32, 1 String 直接指向 Add() 调用。
同事说“PowerShell 函数坏了:什么都返回”。你如何解释这种设计,以及它在什么时候有帮助?
函数是命令,不是方法:它们写入一个流,因此可以在管道中组合,并一次一个地流式产出结果(节省内存,Select-Object -First 可以提前停止)。代价是需要纪律:捕获你不想输出的东西($null =),不要把 return 当成“结果”。作为回报,Get-OpsServer | Test-OpsEndpoint 在最后一台服务器被读取之前就开始测试第一台了。
已验证的教学视频
没有找到专门讲输出语义(ArrayList 泄漏、展开)的已验证视频;请以本模块的复现和 about_Return 为准。
官方文档
视频分镜(约 90 秒)
画面:函数是一个底部开口的盒子;每一行产生值的代码都往开口里掉一个令牌。
旁白:凡是没被捕获的,都会从函数里掉出来。
画面:ArrayList.Add 掉出令牌 0、1、2;一个写着“$null =”的盖子盖住了这一行的开口。
旁白:方法也有返回值。用 $null 等号丢弃它们。
画面:只装一件物品的箱子在出口被拆开;外面再套一层箱子(逗号)的则完整到达。
旁白:集合会被展开;逗号能保住一层。
模块 2 · 作用域:local、script、global、private 与点源
- 说出各个作用域——global(会话)、script(每个脚本文件)、local(当前作用域)以及编号的父作用域——并用
Get-Variable -Scope查看它们。 - 运用两条规则:读取沿调用链向上查找;不带修饰符的赋值只在当前作用域创建或修改变量。
- 有意识地使用
$script:、$global:和$private:,并优先使用返回值而不是共享状态。 - 解释脚本和函数的点源、为什么 OpsKit 加载脚本必须被点源,以及
$using:如何把值传进ForEach-Object -Parallel(第 6 课预览)。
& 与 .)。重要性:★★★★★是什么:一摞作用域
每次运行脚本或函数,PowerShell 都会压入一个新的作用域;返回时,该作用域连同其中的变量一起被丢弃。在提示符下你处于 global 作用域。运行 ./x.ps1 会压入一个 script 作用域;在其中调用函数又会压入一个 local 函数作用域,以此类推。
| 修饰符 | 指向 | 典型用途 |
|---|---|---|
(无)/ $local: | 写入时是当前作用域;读取时是最近的拥有该名称的作用域 | 几乎所有情况 |
$script: | 代码所在脚本文件(或模块,第 4 课)的作用域;在提示符下就是 global 作用域 | 同一脚本/模块内多个函数共享的状态,例如缓存 |
$global: | 会话 | 很少用:需要在脚本结束后依然存在的值。在工具代码中属于坏味道 |
$private: | 当前作用域,对子作用域不可见 | 防止令牌或循环变量泄露给被调用的代码 |
$using: | 调用方变量的副本,被发送到另一个运行空间 | ForEach-Object -Parallel、Start-ThreadJob、Invoke-Command(第 6 课) |
为什么:读穿透,赋值即副本
函数读取 $region 时,PowerShell 先查当前作用域,然后是调用方的作用域,一直到 global(动态作用域——它沿着调用链查找,而不是按代码书写的位置)。函数赋值 $region = 'eastus' 时,会创建一个新的本地变量把父变量遮蔽掉;父变量不变。$count++ 既是读取也是赋值:每次调用都读到父作用域的 0,然后把 1 写进一个新的本地变量。
与 Bash 对比:Bash 函数默认会修改调用方的变量,除非声明为 local。PowerShell 正好相反:凡是你赋值的都是本地的,除非加作用域修饰符。
怎么做:点源
点运算符让脚本或函数在调用方的作用域中运行,而不是新建作用域。配置文件、函数库和 OpsKit 加载脚本都是靠它把函数留下来的:. ~/pslab/OpsKit/OpsKit.ps1。在加载脚本内部,. $file.FullName 把每个函数文件运行在加载脚本的作用域中——因为你点源了加载脚本,那就是你的作用域。
何时:共享状态还是返回值
| 需求 | 推荐 | 避免 |
|---|---|---|
| 函数计算出一个新值 | 返回它:$n = Get-NextCount $n | 在函数内部修改 $script:n |
| 一个模块的多个函数共享缓存 | $script:Cache(第 4 课的模块作用域) | $global:Cache |
| 把辅助函数加载进会话 | 点源一个文件,或导入模块 | 把函数复制粘贴到各个脚本里 |
| 把数据传进并行脚本块 | $using:name(副本) | 指望并行块能看到你的变量 |
$script: 指的是我正在运行的脚本”——它指的是定义该函数的脚本(或模块);在提示符下就是 global。③ “foreach/if 块有自己的作用域”——没有;只有脚本、函数、用 & 调用的脚本块和模块才有。④ “脚本块像闭包一样捕获变量”——除非调用 .GetNewClosure(),它们在调用时读取当前值。⑤ “-Parallel 块能看到我的变量”——它们运行在其他运行空间里;请用 $using:。图解:函数运行时的作用域栈
图解:调用与点源
作用域栈:这个变量住在哪里?
选择一段代码,观察作用域栈:读取的是哪个作用域、写入的是哪个、最后留下了什么。结果在 7.6.10 上复现。
命令参考
| 命令 | 用途 | 说明 |
|---|---|---|
Get-Variable name -Scope 1 | 读取父作用域中的变量 | 0 = 当前,1 = 父级,Global,Script |
Set-Variable name v -Scope Script | 写入指定作用域 | 等同于 $script:name = v |
$script:x、$global:x、$private:x | 作用域修饰符 | 也可用于函数:function global:f {} |
. ./file.ps1、. FunctionName | 在调用方作用域中运行 | 点后面有空格 |
Test-Path variable:name | 变量是否存在(在可见作用域中) | Variable 提供程序 |
$using:name | 把值复制进并行/远程脚本块 | 只读副本 |
{ … }.GetNewClosure() | 把当前变量值冻结进脚本块 | 少用;主要用于事件处理器和补全器 |
$region = 'canadacentral'
function Show-Region { "child sees: $region" }
function Set-Region { $region = 'eastus'; "inside: $region" }
Show-Region
Set-Region
"outside: $region"
child sees: canadacentral inside: eastus outside: canadacentral
$where = 'global'
function Outer {
$where = 'Outer'
function Inner {
"Inner reads `$where = $where"
"scope 1 (Outer): $((Get-Variable where -Scope 1).Value)"
"scope 2 (global): $((Get-Variable where -Scope 2).Value)"
"`$global:where = $global:where"
}
Inner
}
Outer
Inner reads $where = Outer scope 1 (Outer): Outer scope 2 (global): global $global:where = global
如何验证:Inner 定义在 Outer 内部,但起作用的是运行时的调用链:因为是 Outer 调用了 Inner,所以 Outer 的作用域是作用域 1。常见错误:期待词法(C# 式)作用域。生产用法:工具函数不要依赖读取调用方的变量——把它们作为参数传入,这样函数在任何调用方下行为都一样。
$private:token = 's3cr3t'
function Show-Token { "child sees token: [$token]" }
Show-Token
"parent sees token: [$token]"
$mode = 'normal'
function Set-Mode { $mode = 'maintenance' }
Set-Mode; "after call: $mode"
. Set-Mode; "after dot-sourcing: $mode"
child sees token: [] parent sees token: [s3cr3t] after call: normal after dot-sourcing: maintenance
$factor = 10
1..3 | ForEach-Object -Parallel { "$_ x factor = $($_ * $factor)" } -ThrottleLimit 1
1..3 | ForEach-Object -Parallel { "$_ x factor = $($_ * $using:factor)" } -ThrottleLimit 1
1 x factor = 0 2 x factor = 0 3 x factor = 0 1 x factor = 10 2 x factor = 20 3 x factor = 30
没有 $using: 时,$factor 在另一个运行空间中是 $null,$_ * $null 等于 0——不会报错。-ThrottleLimit 1 只是让这个演示的顺序保持稳定;第 6 课会系统讲解并行。
$threshold = 5
$sb = { "threshold is $threshold" }
& $sb
$threshold = 9
& $sb # reads the CURRENT value
$frozen = { "threshold is $threshold" }.GetNewClosure()
$threshold = 1
& $frozen # value captured when the closure was made
threshold is 5 threshold is 9 threshold is 9
目标:复现“变量修改没有生效”,用两种方法修复,并理解为什么 OpsKit 加载脚本必须被点源。环境:pwsh 7.6,~/pslab/scripts。费用:无。
New-Item -ItemType Directory -Path ~/pslab/scripts -Force | Out-Null
Set-Content ~/pslab/scripts/counter.ps1 -Value @'
$count = 0
function Add-Count { $count++; "inside Add-Count: count=$count" }
Add-Count
Add-Count
Add-Count
"after 3 calls: count=$count"
'@
& ~/pslab/scripts/counter.ps1
inside Add-Count: count=1 inside Add-Count: count=1 inside Add-Count: count=1 after 3 calls: count=0
Set-Content ~/pslab/scripts/counter-fixed.ps1 -Value @'
$count = 0
function Add-Count { $script:count++ }
1..3 | ForEach-Object { Add-Count }
"script scope: count=$count"
function Get-NextCount([int]$Current) { $Current + 1 } # better: no shared state
$n = 0
1..3 | ForEach-Object { $n = Get-NextCount $n }
"return value: n=$n"
'@
& ~/pslab/scripts/counter-fixed.ps1
"in my session after the script: count=[$count]"
script scope: count=3 return value: n=3 in my session after the script: count=[]
注意 ForEach-Object { } 里的 $n = … 是有效的:对于 ForEach-Object,脚本块在当前作用域中运行(由 cmdlet 点源执行)。Where-Object 和 ForEach-Object 的脚本块是“脚本块会获得新作用域”这一规则的主要例外。
Set-Content ~/pslab/scripts/lib.ps1 -Value @'
$LibVersion = '1.0'
function Get-LibInfo { "lib $LibVersion" }
'@
& ~/pslab/scripts/lib.ps1
"after &: version=[$LibVersion] function=$([bool](Get-Command Get-LibInfo -ErrorAction Ignore))"
. ~/pslab/scripts/lib.ps1
"after . : version=[$LibVersion] function=$([bool](Get-Command Get-LibInfo -ErrorAction Ignore))"
after &: version=[] function=False after . : version=[1.0] function=True
& ~/pslab/OpsKit/OpsKit.ps1 Get-Command Get-OpsServer
Get-Command: The term 'Get-OpsServer' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
$script: 就是 global:
function Set-Last { $global:OpsLastRun = Get-Date -Format 'HH:mm'; $script:OpsMode = 'set by function' }
Set-Last
Test-Path variable:OpsLastRun
$OpsMode
True set by function
Remove-Variable OpsLastRun, OpsMode, LibVersion -ErrorAction Ignore;~/pslab/scripts 中的文件可保留也可删除。案例 1:永远达不到上限的重试计数器
问题:部署脚本用 function Invoke-WithRetry { … $attempt++ … if ($attempt -ge 5) { throw } } 重试 API 调用,脚本级有 $attempt = 0。遇到持续失败的端点时它无限循环。根因:$attempt++ 每次调用都创建本地副本(永远是 1)。修复:把计数器放在函数内部(for 循环)——第 5 课会为 OpsKit v0.3 写一个正规的重试辅助函数。预防:函数只应依赖它的参数。
案例 2:“在我的控制台里能用,计划任务里不行”
问题:一个函数读取 $ConfigPath,但没有把它声明为参数。在作者的控制台中,这个变量存在(在他的配置文件里设置);计划任务以 -NoProfile 运行,函数拿到的是 $null。根因:动态作用域悄悄读取了一个全局变量。修复:把它变成带默认值的参数([string]$ConfigPath = (Join-Path $PSScriptRoot 'config.psd1'))。Set-StrictMode -Version Latest(第 5 课)会把读取从未赋值的变量变成错误。
案例 3:什么都没测的并行健康检查
问题:$servers | ForEach-Object -Parallel { Test-Connection $_ -TimeoutSeconds $timeout } 到处都用了默认超时。根因:并行运行空间中不存在 $timeout。修复:$using:timeout。第 6 课的 Invoke-OpsHealthCheck 会使用这种模式。
常见错误与修复
函数内修改的变量在函数结束后没有变化
原因:赋值即副本。
$x = 1
function f { $x = 2; "local: $((Get-Variable x -Scope 0).Value) parent: $((Get-Variable x -Scope 1).Value)" }
f
修复:返回新值;需要刻意共享状态时用 $script:x。
运行函数库脚本之后立刻出现 The term 'X' is not recognized …
原因:脚本是用 & 或 ./ 运行的,而不是点源。
修复:. ./lib.ps1(点、空格、路径),或把它改成模块(第 4 课)。
在 ForEach-Object -Parallel / Start-ThreadJob / Invoke-Command 中某个值是 $null
原因:不同的运行空间。
修复:$using:var,或通过 -ArgumentList 传入。
The variable '$x' cannot be retrieved because it has not been set.
原因:启用了 Set-StrictMode -Version Latest,而这个名字在任何可见作用域中都从未赋值——通常是拼写错误。
function Get-Total { $total = 0; foreach ($i in 1..3) { $total += $i }; $totla }
Set-StrictMode -Version Latest
Get-Total
InvalidOperation: The variable '$totla' cannot be retrieved because it has not been set.
没有严格模式时,同一个函数会悄无声息地什么都不返回。
1. 证明 if 和 foreach 块不创建作用域,而用 & 调用的脚本块会创建。
$v = 1
if ($true) { $v = 2 }; "after if: $v" # 2
foreach ($i in 1) { $v = 3 }; "after foreach: $v" # 3
& { $v = 4 }; "after & {}: $v" # 3
. { $v = 5 }; "after . {}: $v" # 52. 列出当前作用域自己定义的变量,不含继承来的。
Get-Variable -Scope 0 | Select-Object -First 10 Name
同事的配置文件定义了 $Env = 'prod'。你的函数 Get-OpsServer 有一个 -Env 参数。有人不带 -Env 调用 Get-OpsServer 时会冲突吗?
不会。声明过的参数始终是函数自身作用域中的变量;如果没有传入,它取默认值(这里是 $null),从而遮蔽全局的 $Env(已验证:仍返回全部 12 台服务器)。危险的是相反的情况——函数意外读取了一个未声明的变量。(注意变量 $Env 与 $env:PATH 是两回事:env: 是驱动器限定符。)
已验证的教学视频
官方文档
- about_Scopes · about_Script_Blocks · about_Remote_Variables($using:)
视频分镜(约 90 秒)
画面:叠放的玻璃盒子(global、script、function);一只手穿过它们向下读取 $region。
旁白:读取会向上穿过每一个调用方。
画面:$count++ 在最上面的盒子里复制一份;返回时这个盒子被扔掉。
旁白:写入会创建本地副本——所以计数器一直是零。
画面:脚本路径前的一个点把它的盒子合并进你的盒子。
旁白:点源函数库;用返回值代替共享状态。
模块 3 · 高级函数:[CmdletBinding()]、通用参数与 $PSCmdlet
-Verbose 和 -ErrorAction 直接可用,$PSCmdlet / $PSBoundParameters 告诉你自己是如何被调用的- 用
[CmdletBinding()](或任意[Parameter()]特性)把函数变成高级函数,并列出它在 7.6 中获得的 12 个通用参数。 - 对比绑定行为:简单函数把未知实参吞进
$args(第 1 课的-joinbug);高级函数会以 “A parameter cannot be found …” 拒绝它们。 - 用
Write-Verbose/Write-Debug输出诊断信息,观察-Verbose如何传递给函数调用的命令;用Write-Error遵守-ErrorAction。 - 使用
$PSCmdlet(ParameterSetName、MyInvocation、ThrowTerminatingError)和$PSBoundParameters(参数是真的传入了,还是默认值?)。
[<CommonParameters>])。重要性:★★★★★是什么:高级函数就是脚本 cmdlet
当函数的 param() 块带有 [CmdletBinding()],或者任意参数带有 [Parameter()] 特性时,它就成为高级函数(已验证:两种情况下 (Get-Command f).CmdletBinding 都是 True)。从此,第 1 课中你为 Get-Content 跟踪过的那个参数绑定器也会绑定你的函数,函数还会得到一个 $PSCmdlet 对象,提供 C# cmdlet 的大部分 API。
| 特性 | 简单函数 | 高级函数 |
|---|---|---|
未知的命名实参 -Nmae x | 悄悄放进 $args | 错误:A parameter cannot be found that matches parameter name 'Nmae'. |
| 多余的位置实参 | 放进 $args | 错误:A positional parameter cannot be found that accepts argument … |
| 通用参数 | 无 | 12 个:Verbose, Debug, ErrorAction, WarningAction, InformationAction, ProgressAction, ErrorVariable, WarningVariable, InformationVariable, OutVariable, OutBuffer, PipelineVariable |
$PSCmdlet | $null | ParameterSetName、MyInvocation、WriteError、ThrowTerminatingError、ShouldProcess(第 5 课) |
| 参数特性 | 只有类型 | Mandatory、Position、ValueFromPipeline、参数集、校验 |
$args | 未绑定的实参 | 永远为空 |
为什么:在入口处大声失败
第 1 课的综合实验丢失了一个 -join ',',因为 New-Check 是简单函数:单词 -join 和 ',' 落进了 $args,没人去看。高级函数会把同样的错误变成立即、准确的报错。对于会修改生产系统的工具,像 -Enviroment prod 这样的拼写错误必须让命令停下来,而不是带着默认值运行。
怎么做:结构剖析
function Get-Data {
[CmdletBinding()] # attribute on the param block
param([string]$Env = 'dev')
Write-Verbose "Loading inventory for $Env" # shown only with -Verbose
Write-Debug "raw env value: [$Env]" # shown only with -Debug
$n = (Import-Csv ~/pslab/data/servers.csv | Where-Object Env -eq $Env).Count
Write-Verbose "Found $n servers"
$n # output
}
-Verbose 会在函数内部设置 $VerbosePreference = 'Continue';因为首选项变量就是沿作用域链读取的普通变量,所以从这里调用的所有函数和 cmdlet 也会变得详细。PowerShell 7 中的 -Debug 设置 $DebugPreference = 'Continue'(Windows PowerShell 5.1 用的是 Inquire,每条消息都会提示)。
何时:$PSBoundParameters 与变量本身
$Port 总是有值(没传就是默认值)。$PSBoundParameters 是一个字典,只包含调用方实际绑定的参数(包括 Verbose=True 这样的通用参数)。当“没有传入”和“传入了与默认值相同的值”需要不同行为时,用 $PSBoundParameters.ContainsKey('Port')——Get-OpsConfig 就靠它回退到配置文件中的 DefaultEnv。模块 7 用同一个字典做转发(@PSBoundParameters)。
[CmdletBinding()] 只是为了 -Verbose”——它最大的价值是严格绑定和 cmdlet API。② “默认值会出现在 $PSBoundParameters 里”——不会。③ “Write-Verbose 的输出是结果的一部分”——它是 4 号流,$x = f 永远捕获不到。④ “-Debug 会提示确认”——只有 Windows PowerShell 5.1 会。⑤ “要用 [Parameter(Mandatory)] 必须先写 [CmdletBinding()]”——任何 [Parameter()] 都已经让函数成为高级函数;为了清晰,还是写上 [CmdletBinding()]。图解:[CmdletBinding()] 带来了什么
图解:首选项的传递
简单函数与高级函数:同一调用,两种结果
选择一个调用,分别观察简单函数(无特性)和它的高级版本如何绑定。结果在 7.6.10 上复现。
命令参考
| 语法 | 用途 | 说明 |
|---|---|---|
[CmdletBinding()] param(…) | 让函数成为高级函数 | 选项:DefaultParameterSetName、SupportsShouldProcess(第 5 课)、PositionalBinding |
Write-Verbose "…" / -Verbose | 可选的诊断信息 | 4 号流 |
Write-Debug "…" / -Debug | 开发者细节 | 5 号流;7.x 中不再提示 |
Write-Error "…" | 遵守 -ErrorAction 的非终止错误 | 细节见第 5 课 |
$PSCmdlet.ThrowTerminatingError($record) | 用规范的 ErrorRecord 停止 | 错误指向调用方那一行,而不是函数内部 |
$PSCmdlet.ParameterSetName | 选中了哪个参数集 | 模块 4 |
$PSBoundParameters.ContainsKey('X') | 是否传入了 -X? | 不包含默认值 |
(Get-Command f).CmdletBinding | f 是高级函数吗? | True/False |
function Get-Simple { param([string]$Name) "Hello $Name; args=[$($args -join ',')]" }
function Get-Advanced { [CmdletBinding()] param([string]$Name) "Hello $Name" }
Get-Simple -Nmae ops
Get-Advanced -Nmae ops
Get-Simple ops extra1 extra2
Get-Advanced ops extra1
Hello ; args=[-Nmae,ops] Get-Advanced: A parameter cannot be found that matches parameter name 'Nmae'. Hello ops; args=[extra1,extra2] Get-Advanced: A positional parameter cannot be found that accepts argument 'extra1'.
(Get-Command Get-Simple).Parameters.Keys -join ', ' (Get-Command Get-Advanced).Parameters.Keys -join ', '
Name Name, Verbose, Debug, ErrorAction, WarningAction, InformationAction, ProgressAction, ErrorVariable, WarningVariable, InformationVariable, OutVariable, OutBuffer, PipelineVariable
如何验证:列表里有 ProgressAction——它在 7.4 中加入,所以把通用参数展开传给 Windows PowerShell 5.1 命令的脚本可能会被它绊倒。常见错误:在高级函数中自己定义 -Verbose 或 -ErrorAction 参数(错误:同名参数被定义了多次)。生产用法:模块中的每一个函数都写成高级函数;PSScriptAnalyzer(第 8 课)会提示缺少 [CmdletBinding()]。
Get-Data -Env prod
Get-Data -Env prod -Verbose
Get-Data -Env prod -Debug
function Invoke-Outer { [CmdletBinding()] param() Write-Verbose 'outer'; Get-Data -Env dev }
Invoke-Outer -Verbose
6 VERBOSE: Loading inventory for prod VERBOSE: Found 6 servers 6 DEBUG: raw env value: [prod] 6 VERBOSE: outer VERBOSE: Loading inventory for dev VERBOSE: Found 3 servers 3
function Show-Invocation {
[CmdletBinding(DefaultParameterSetName = 'ByName')]
param(
[Parameter(ParameterSetName = 'ByName', Position = 0)] [string]$Name,
[Parameter(ParameterSetName = 'ById')] [int]$Id,
[int]$Port = 8080
)
"ParameterSetName : $($PSCmdlet.ParameterSetName)"
"Command : $($PSCmdlet.MyInvocation.MyCommand.Name)"
"Line : $($PSCmdlet.MyInvocation.Line.Trim())"
"BoundParameters : $(($PSBoundParameters.GetEnumerator() | ForEach-Object { '{0}={1}' -f $_.Key, $_.Value }) -join '; ')"
"Port was passed? : $($PSBoundParameters.ContainsKey('Port')) (value $Port)"
}
Show-Invocation web-01
Show-Invocation -Id 7 -Port 443 -Verbose
ParameterSetName : ByName Command : Show-Invocation Line : Show-Invocation web-01 BoundParameters : Name=web-01 Port was passed? : False (value 8080) ParameterSetName : ById Command : Show-Invocation Line : Show-Invocation -Id 7 -Port 443 -Verbose BoundParameters : Id=7; Port=443; Verbose=True Port was passed? : True (value 443)
目标:升级一个简单函数,证明有哪些变化,并使用 cmdlet API。环境:pwsh 7.6,~/pslab。费用:无。
function New-Check {
[CmdletBinding()]
param([string]$Name, $Expected, $Actual)
"$Name expected=$Expected actual=$Actual"
}
New-Check 'envs' 'a,b' ('b', 'a' | Sort-Object) -join ','
New-Check 'envs' 'a,b' (('b', 'a' | Sort-Object) -join ',')
New-Check: A parameter cannot be found that matches parameter name 'join'. envs expected=a,b actual=a,b
Get-Data,分别带和不带 -Verbose、-Debug 运行(输出见“命令”分页)。然后捕获结果:$n = Get-Data -Env prod -Verbose——VERBOSE 行出现在屏幕上,$n 只是 6。-ErrorAction 对你的函数生效:
function Get-Thing {
[CmdletBinding()]
param([string]$Name)
if ($Name -eq 'bad') { Write-Error "Get-Thing: cannot find '$Name'"; return }
"thing $Name"
}
Get-Thing bad -ErrorAction SilentlyContinue; 'continued after SilentlyContinue'
try { Get-Thing bad -ErrorAction Stop } catch { "caught: $($_.Exception.Message)" }
Get-Thing bad -ErrorVariable ev -ErrorAction SilentlyContinue; "ErrorVariable holds: $ev"
continued after SilentlyContinue caught: Get-Thing: cannot find 'bad' ErrorVariable holds: Get-Thing: cannot find 'bad'
function Get-Strict {
[CmdletBinding()]
param([string]$Path)
if (-not (Test-Path -LiteralPath $Path)) {
$err = [System.Management.Automation.ErrorRecord]::new(
[System.IO.FileNotFoundException]::new("Inventory not found: $Path"),
'OpsKit.InventoryNotFound', 'ObjectNotFound', $Path)
$PSCmdlet.ThrowTerminatingError($err)
}
'found'
}
Get-Strict ./nope.json
$Error[0].FullyQualifiedErrorId
$Error[0].CategoryInfo.Category
Get-Strict: Inventory not found: ./nope.json OpsKit.InventoryNotFound,Get-Strict ObjectNotFound
function Get-Pos { [CmdletBinding()] param([string]$A, [string]$B) "A=$A B=$B" }
function Get-NoPos { [CmdletBinding(PositionalBinding = $false)] param([string]$A, [string]$B) "A=$A B=$B" }
Get-Pos one two
Get-NoPos one two
A=one B=two Get-NoPos: A positional parameter cannot be found that accepts argument 'one'.
案例 1:一个拼写错误重置了生产应用池
问题:Reset-AppPool -Enviroment prod(拼错了)回收的是dev 应用池——默认值——值班工程师以为 prod 已经修好了。根因:简单函数;拼错的参数进了 $args。修复:[CmdletBinding()] 加上 [ValidateSet()],并且环境参数不设默认值(模块 5)。预防:代码评审清单(以及第 8 课在 CI 中运行的 PSScriptAnalyzer)要求共享模块中的函数都是高级函数。
案例 2:CI 中永远看不到 verbose 日志
问题:一个模块为了“能在 CI 中显示”而用 Write-Host 输出进度,结果输出既无法静音也无法捕获。修复:全部改用 Write-Verbose;需要调试时,流水线步骤给入口脚本加 -Verbose。首选项的传递会让所有内部函数自动变得详细。
案例 3:被包装函数忽略的 -ErrorAction Stop
问题:try { Sync-Inventory -ErrorAction Stop } catch { … } 从来没捕获到任何东西。根因:Sync-Inventory 是简单函数:它没有通用参数,其中的 Write-Error 使用的是调用方的首选项(Continue)。在 7.6 中,传给它的 -ErrorAction 只是落进了 $args。修复:把它改成高级函数,这样 -ErrorAction Stop 会在其内部设置 $ErrorActionPreference。
常见错误与修复
A parameter cannot be found that matches parameter name 'X'.
原因:拼写错误、参数集不对,或者在参数模式中出现了 -join/-split 这样的运算符(用括号把表达式包起来)。
Get-Command MyFunc -Syntax
A positional parameter cannot be found that accepts argument 'x'.
原因:位置实参比位置参数多;常见原因是数组少了逗号(写成 -Tag web api 而不是 -Tag web, api),或者设置了 PositionalBinding = $false。
A parameter with the name 'Verbose' was defined multiple times for the command.
原因:你在高级函数中自己声明了一个通用参数。
修复:删掉它;如果需要知道是否启用,用 $PSBoundParameters['Verbose'] 或 $VerbosePreference。
Write-Verbose 什么都不输出
原因:函数是简单函数(没有 -Verbose 参数),或者在函数内部把 $VerbosePreference 设成了 SilentlyContinue。
修复:加上 [CmdletBinding()];用 (Get-Command f).CmdletBinding 检查。
1. 列出当前会话中定义的所有高级函数。
Get-Command -CommandType Function | Where-Object CmdletBinding | Select-Object Name, Source
2. 编写 Get-Port:当没有传入 -Port、使用默认值 8080 时给出 verbose 提示。
function Get-Port {
[CmdletBinding()]
param([int]$Port = 8080)
if (-not $PSBoundParameters.ContainsKey('Port')) { Write-Verbose "No -Port given; using $Port" }
$Port
}
Get-Port -Verbose团队想把 200 个简单函数转换成高级函数。可能会破坏什么?
依赖 $args 或传入多余/拼错实参的调用方现在会失败(这正是目的——修复它们)。自己声明了 $Verbose/$Debug 参数的函数会加载失败。位置调用可能绑定得不一样,因为除非设置 PositionalBinding = $false,每个参数现在都按声明顺序获得一个位置。读取 $input 而不是声明管道参数的函数需要一个管道参数和 process 块(模块 6)。请配合测试逐步推进。
已验证的教学视频
官方文档
- about_Functions_Advanced · about_Functions_CmdletBindingAttribute · about_Functions_Advanced_Methods($PSCmdlet)· about_CommonParameters
视频分镜(约 90 秒)
画面:调用“-Nmae ops”走向两扇门;简单函数的门让它溜进一个标着 $args 的袋子,高级函数的门把它拦下。
旁白:一个特性,把静默的拼写错误变成明确的报错。
画面:一个 -Verbose 开关点亮了函数里的灯,也点亮了它调用的每个房间。
旁白:通用参数白送,首选项沿调用链向下传递。
画面:一块写着 $PSBoundParameters 的写字板,只列出调用方写了什么。
旁白:PSBoundParameters 告诉你调用方真正传了什么。
模块 4 · 参数:类型、Mandatory、Position、开关与参数集
Mandatory 和 Position 决定语法图的样子,[switch] 表达是/否,参数集描述哪些组合是合法的- 选择参数类型并预测转换结果(
'8080'→ 8080,8080.6→ 8081,'abc'→ 错误;[bool]拒绝字符串)。 - 使用
[Parameter(Mandatory)]、HelpMessage、[AllowEmptyString()],并了解必需参数在交互模式和-NonInteractive下的行为。 - 设置 Position 和默认值(包括使用前面参数的表达式),并正确使用
[switch](-Force:$false,绝不默认为$true)。 - 用
DefaultParameterSetName设计参数集,读懂生成的语法图,按$PSCmdlet.ParameterSetName分支,并添加别名。
是什么:参数声明的组成部分
[Parameter(Mandatory, Position = 0, ParameterSetName = 'ByName', HelpMessage = '…')]
[Alias('Address')] # extra names (also used for pipeline ByPropertyName, Module 6)
[ValidateSet('dev', 'prod')] # validation (Module 5)
[string[]] # type: conversion happens BEFORE validation
$Name = 'default' # default (ignored when Mandatory)
为什么:类型替你完成解析
| 类型 | 输入 | 结果(7.6.10) |
|---|---|---|
[int] | '8080' | 8080(Int32) |
[int] | 8080.6 | 8081——四舍五入,不报错 |
[int] | abc | Cannot process argument transformation on parameter 'Port'. Cannot convert value "abc" to type "System.Int32". |
[string[]] | web / web, api | 1 个 / 2 个元素的数组——一个参数两种都接受 |
[ipaddress] | 10.30.1.999 | … Error: "An invalid IP address was specified." |
[bool] | 'false' | 错误:Boolean parameters accept only Boolean values and numbers——请用 [switch] |
怎么做:Mandatory、Position、默认值、开关
- Mandatory:缺失时,交互式宿主会提示输入(Supply values for the following parameters);在
-NonInteractive下调用会失败。必需的[string]还会拒绝''和$null,除非加上[AllowEmptyString()]/[AllowNull()]。 - Position:让调用方可以省略参数名。在高级函数中,没有显式
Position的参数按声明顺序成为位置参数——除非有任何参数声明了 Position,那时只有声明过的才是位置参数(已验证)。只给一两个最明显的参数设置位置。 - 默认值在调用时按声明顺序求值,所以后面的默认值可以使用前面的参数(
$Scheme = $(if ($Port -eq 443) {'https'} else {'http'}))。 [switch]:出现即为$true。-Force:$false和-Force:$var显式传值(转发时需要)。绝不要给开关设默认值$true:调用方只能用别扭的-Switch:$false关掉它。
何时:参数集
当标识目标的方式互相排斥(按名称、按环境、按 IP)时使用参数集。每个参数属于一个或多个参数集;没有 ParameterSetName 的参数属于所有参数集。绑定器挑选与所提供参数匹配的参数集。如果仍有多个参数集都可能,由 DefaultParameterSetName 决定;没有它,就会得到 “Parameter set cannot be resolved using the specified named parameters”。
[int] 会拒绝小数”——它会四舍五入。② “[bool] 参数和开关一样”——它必须有值,而且拒绝 'false'。③ “必需参数会快速失败”——交互模式下它会提示输入,没有 -NonInteractive 时可能让自动化任务挂住。④ “不属于任何参数集的参数不在任何集里”——它们在所有集里(__AllParameterSets)。⑤ “默认值也会用于 Mandatory 参数”——永远不会;而且校验不会作用于默认值(模块 5)。图解:Get-Node 的三个参数集
图解:绑定器如何确定参数集
参数集解析器
选择一个 Get-Node 调用(定义见“命令”分页),观察绑定器如何缩小候选参数集。结果在 7.6.10 上复现。
命令参考
| 语法 | 用途 | 说明 |
|---|---|---|
[Parameter(Mandatory)] | 必需 | 交互时提示;输入 !? 显示 HelpMessage |
[Parameter(Position = 0)] | 参数名可省略 | 语法中显示为 [-Name] |
[Parameter(ParameterSetName = 'X')] | 属于某个参数集 | 属于多个集时重复该特性 |
[CmdletBinding(DefaultParameterSetName = 'X')] | 决胜规则 | 一旦有参数集就应该设置 |
[switch]$Force | 开/关标志 | 显式传值用 -Force:$false |
[Alias('CN')] | 备用名称 | 也参与 ByPropertyName 绑定 |
[AllowEmptyString()]、[AllowNull()]、[AllowEmptyCollection()] | 放宽 Mandatory 检查 | 用于“存在但为空”的值 |
Get-Command f -Syntax | 查看生成的语法 | 每个参数集一行 |
function Test-Port {
[CmdletBinding()]
param([int]$Port, [string[]]$Tag)
"Port=$Port ($($Port.GetType().Name)) Tags=$($Tag.Count)"
}
Test-Port -Port '8080' -Tag web
Test-Port -Port 8080.6 -Tag web, api
Test-Port -Port abc
function Test-Flag { [CmdletBinding()] param([bool]$Enabled) "Enabled=$Enabled" }
Test-Flag -Enabled 'false'
Port=8080 (Int32) Tags=1 Port=8081 (Int32) Tags=2 Test-Port: Cannot process argument transformation on parameter 'Port'. Cannot convert value "abc" to type "System.Int32". Error: "The input string 'abc' was not in a correct format." Test-Flag: Cannot process argument transformation on parameter 'Enabled'. Cannot convert value "System.String" to type "System.Boolean". Boolean parameters accept only Boolean values and numbers, such as $True, $False, 1 or 0.
function Get-Server {
[CmdletBinding()]
param(
[Parameter(Mandatory, HelpMessage = 'Environment: dev, staging or prod')]
[string]$Env
)
"env=$Env"
}
Get-Server -Env ''
pwsh -NoProfile -NonInteractive -Command 'function Get-Server { [CmdletBinding()] param([Parameter(Mandatory)][string]$Env) "env=$Env" }; Get-Server'
"exit code: $LASTEXITCODE"
Get-Server: Cannot bind argument to parameter 'Env' because it is an empty string. Get-Server: Cannot process command because of one or more missing mandatory parameters: Env. exit code: 1
如何验证:在交互式控制台中,不带 -Env 运行 Get-Server 会出现提示;输入 !? 可以看到 HelpMessage。常见错误:由调度程序运行、却没有 -NonInteractive 的脚本带有必需参数——作业会卡在提示上。生产用法:把环境/目标参数设为必需,其他参数都给安全的默认值。
function Get-Node {
[CmdletBinding(DefaultParameterSetName = 'ByEnv')]
param(
[Parameter(ParameterSetName = 'ByName', Mandatory, Position = 0)]
[string]$Name,
[Parameter(ParameterSetName = 'ByEnv')]
[string]$Env = 'dev',
[Parameter(ParameterSetName = 'ByIP', Mandatory)]
[Alias('Address')]
[ipaddress]$IP,
[int]$Port = 8080
)
"set=$($PSCmdlet.ParameterSetName) " + $(switch ($PSCmdlet.ParameterSetName) {
'ByName' { "name=$Name" } 'ByEnv' { "env=$Env" } 'ByIP' { "ip=$IP" } })
}
Get-Command Get-Node -Syntax
Get-Node
Get-Node web-01
Get-Node -Env prod -Port 443
Get-Node -Address 10.30.1.41
Get-Node -Name web-01 -Env prod
Get-Node -IP 10.30.1.999
Get-Node [-Env <string>] [-Port <int>] [<CommonParameters>] Get-Node [-Name] <string> [-Port <int>] [<CommonParameters>] Get-Node -IP <ipaddress> [-Port <int>] [<CommonParameters>] set=ByEnv env=dev set=ByName name=web-01 set=ByEnv env=prod set=ByIP ip=10.30.1.41 Get-Node: Parameter set cannot be resolved using the specified named parameters. One or more parameters issued cannot be used together or an insufficient number of parameters were provided. Get-Node: Cannot process argument transformation on parameter 'IP'. Cannot convert value "10.30.1.999" to type "System.Net.IPAddress". Error: "An invalid IP address was specified."
(Get-Command Get-Node).Parameters.Values |
Where-Object Name -in 'Name', 'Env', 'IP', 'Port' |
Format-Table Name, ParameterType, @{ n = 'Sets'; e = { $_.ParameterSets.Keys -join ',' } }, Aliases -AutoSize
Name ParameterType Sets Aliases
---- ------------- ---- -------
Name System.String ByName {}
Env System.String ByEnv {}
IP System.Net.IPAddress ByIP {Address}
Port System.Int32 __AllParameterSets {}
目标:构建有三个参数集的 Get-Node,然后探索默认值和开关。环境:pwsh 7.6。费用:无。
Get-Node,运行那七个调用,并与语法图对照。然后删除 DefaultParameterSetName,不带参数运行 Get-Node——解释出现的错误。function Get-Node2 {
[CmdletBinding()]
param(
[Parameter(ParameterSetName = 'ByName')] [string]$Name,
[Parameter(ParameterSetName = 'ByEnv')] [string]$Env
)
"set=$($PSCmdlet.ParameterSetName)"
}
Get-Node2
Get-Node2 -Name a
Get-Node2: Parameter set cannot be resolved using the specified named parameters. One or more parameters issued cannot be used together or an insufficient number of parameters were provided. set=ByName
function New-Url {
[CmdletBinding()]
param(
[string]$HostName = 'localhost',
[int]$Port = 8080,
[string]$Scheme = $(if ($Port -eq 443) { 'https' } else { 'http' })
)
"{0}://{1}:{2}" -f $Scheme, $HostName, $Port
}
New-Url
New-Url -Port 443 -HostName shop.example.com
http://localhost:8080 https://shop.example.com:443
function Remove-Cache {
[CmdletBinding()]
param([switch]$Force)
"Force.IsPresent=$($Force.IsPresent) if(`$Force)=$(if ($Force) { 'yes' } else { 'no' }) type=$($Force.GetType().Name)"
}
Remove-Cache
Remove-Cache -Force
Remove-Cache -Force:$false
$wantForce = $true; Remove-Cache -Force:$wantForce
Force.IsPresent=False if($Force)=no type=SwitchParameter Force.IsPresent=True if($Force)=yes type=SwitchParameter Force.IsPresent=False if($Force)=no type=SwitchParameter Force.IsPresent=True if($Force)=yes type=SwitchParameter
function Set-Note {
[CmdletBinding()]
param([Parameter(Mandatory)] [AllowEmptyString()] [string]$Text)
"note=[$Text]"
}
Set-Note -Text ''
note=[]
Get-Node -Addr 10.30.1.41 可以工作(别名 Address 的唯一前缀),输出 set=ByIP ip=10.30.1.41。在提示符下缩写没问题;在脚本中请始终写全参数名(第 1 课模块 3)。案例 1:一个“挂了”三天的夜间作业
问题:一次重构给清理脚本加上了 [Parameter(Mandatory)] $Region,之后计划任务再也没结束。根因:任务运行 pwsh -File cleanup.ps1,既没有传 -Region,也没有 -NonInteractive;PowerShell 在一个看不见的会话里等待提示输入。修复:传入该值,并且计划任务一律使用 -NoProfile -NonInteractive,它会把提示变成立即的错误(退出码 1)。
案例 2:-Recurse $true 什么都没做
问题:一个包装函数声明了 [bool]$Recurse = $true,调用方写 -Recurse(不带值)——报错——或者 -Recurse 0。修复:改为 [switch]$Recurse,并以 -Recurse:$Recurse 转发。默认值为 $true 的开关是一种设计坏味道:给它改个名字(-NoRecurse)。
案例 3:两种标识 VM 的方式同时给出
问题:Stop-LabVm -Name web-01 -Id 42 停掉了 42 号 VM,而它并不是 web-01;函数悄悄优先使用了 $Id。修复:把 -Name 和 -Id 放进不同的参数集;绑定器会在任何东西被停止之前拒绝这个有歧义的调用。
常见错误与修复
Parameter set cannot be resolved using the specified named parameters.
原因:组合了来自两个参数集的参数,或者有多个参数集匹配而没有 DefaultParameterSetName。
Get-Command f -Syntax (Get-Command f).ParameterSets | Select-Object Name, IsDefault
Cannot process argument transformation on parameter 'X'. Cannot convert value …
原因:实参无法转换成声明的类型(把数组传给标量参数时也会出现)。
修复:传入正确的类型,或者有意识地放宽类型([string[]])。
Cannot bind argument to parameter 'X' because it is an empty string / is null.
原因:Mandatory 参数拒绝空值。
修复:修正调用方;如果空值是合法的,加上 [AllowEmptyString()] / [AllowNull()]。
Cannot process command because of one or more missing mandatory parameters: X.
原因:处于 -NonInteractive 会话中,而必需参数没有提供(或者管道对象缺少它,模块 6)。
1. 查看 Get-ChildItem 和你的 Get-Node 的默认参数集。
(Get-Command Get-ChildItem).ParameterSets | Select-Object Name, IsDefault (Get-Command Get-Node).DefaultParameterSet
2. 添加一个 -Tag 参数,只在 ByEnv 参数集中为必需。
[Parameter(ParameterSetName = 'ByEnv', Mandatory)] [Parameter(ParameterSetName = 'ByName')] [string[]]$Tag
每个参数集重复一次 [Parameter()] 特性;每个副本可以有不同的 Mandatory/Position 值。
设计 Get-OpsConfig 的参数:它返回某个环境的设置,或整个配置。为什么用一个单独参数集里的开关,而不是 -Env all?
两种模式返回不同类型(OpsKit.EnvConfig 对象与哈希表)——这是使用两个参数集、各自带 [OutputType](模块 7)的强烈信号。像 'all' 这样的魔法值必须被 ValidateSet 允许,会作为一个“环境”出现在 Tab 补全中,还需要到处特殊处理。有了参数集,Get-OpsConfig -Env prod -All 会被绑定器免费拒绝(模块 8 展示了真实错误)。
已验证的教学视频
官方文档
视频分镜(约 90 秒)
画面:一张有类型字段的表单;'8080' 滑进 Int 框,'abc' 被弹开。
旁白:参数类型在你的代码运行之前就转换或拒绝输入。
画面:三扇门分别标着 ByName、ByEnv、ByIP;一个拿着两把钥匙的调用被挡回。
旁白:参数集描述合法的组合。
画面:一个标着 -Force 的电灯开关。
旁白:是/否选项用开关——绝不用默认为 true 的布尔值。
模块 5 · 校验与补全:Validate* 特性与参数补全器
- 选择合适的特性:
ValidateSet、ValidatePattern、ValidateRange(包括'Positive')、ValidateScript、ValidateNotNullOrEmpty、ValidateNotNullOrWhiteSpace、ValidateCount、ValidateLength。 - 认识每个特性的错误信息,并用
ErrorMessage = '… {0} …'替换难懂的信息。 - 掌握边界:校验在类型转换之后运行,不作用于默认值,但之后每次给参数变量赋值都会再次校验。
- 用
ValidateSet(免费附送)、[ArgumentCompleter()]、[ArgumentCompletions()]和Register-ArgumentCompleter提供补全,并用TabExpansion2在不按键盘的情况下测试补全器。
是什么:校验特性
| 特性 | 检查内容 | 错误信息开头(7.6.10) |
|---|---|---|
[ValidateSet('dev','staging','prod')] | 固定列表之一;默认不区分大小写(用 IgnoreCase = $false 改变);还提供 Tab 补全 | The argument "qa" does not belong to the set "dev,staging,prod" … |
[ValidatePattern('^[a-z]+-\d{2}$')] | 正则匹配(不区分大小写) | The argument "Web_3" does not match the "^[a-z]+-\d{2}$" pattern … |
[ValidateRange(1, 60)]、[ValidateRange('Positive')] | 数值范围;类别有 Positive、NonNegative、Negative、NonPositive | The 0 argument is less than the minimum allowed range of 1 … |
[ValidateScript({ Test-Path $_ })] | 任意条件;必须返回 $true | The " Test-Path -LiteralPath $_ " validation script … did not return a result of True |
[ValidateNotNullOrEmpty()] | 不是 $null、'' 或空集合 | The argument is null or empty … |
[ValidateNotNullOrWhiteSpace()](7.4+) | 还拒绝 ' ' | … consists of only white-space characters … |
[ValidateCount(1, 3)]、[ValidateLength(1, 10)] | 元素个数 / 字符串长度 | The parameter requires at least 1 value(s) and no more than 3 … |
为什么:在任何副作用之前拒绝错误输入
校验在绑定器中运行,早于 begin/process。会重启服务或删除备份的工具,绝不应该带着 -Env qa 或 -Keep 0 开始干活。校验也记录了意图:Get-Help 和语法图体现了这些特性的效果,ValidateSet 的值会出现在 Tab 补全中。
怎么做:自定义错误信息
ValidatePattern 和 ValidateScript 接受 ErrorMessage,其中 {0} 是值({1} 是模式或脚本)。对比 “The " Test-Path -LiteralPath $_ " validation script for the argument with value "./nope.json" did not return a result of True” 和 “File not found: ./nope.json”。在 ValidateScript 里也可以 throw "…" 来给出自己的信息。
何时:只补全、不限制
| 机制 | 限制取值? | 适用于 |
|---|---|---|
ValidateSet | 是 | 固定的小列表(环境) |
[ArgumentCompletions('a','b')] | 否 | 常用建议,也允许其他值 |
[ArgumentCompleter({ … })] | 否 | 补全时动态计算的建议(来自清单的区域) |
Register-ArgumentCompleter | 否 | 给别人的命令加补全,或在配置文件/模块中添加而不修改函数 |
[ValidateRange(1,10)][int]$N = 99 照样带着 99 运行。② “校验只发生一次”——之后给参数变量赋值会再次校验(The variable cannot be validated because the value 12 is not a valid value for the Limit variable)。③ “ValidateSet 区分大小写”——默认不区分,而且值保留调用方的大小写(PROD)。④ “补全器会校验”——补全器只给建议;-Region eastus 仍会被绑定。⑤ “ValidateScript 可以使用其他参数”——不可靠:它们可能还没绑定;跨参数检查应放在函数体中。图解:校验在绑定中的位置
图解:Tab 补全如何询问你的代码
校验关卡:哪个特性拦下了这个值?
选择一个实参,逐步经过类型转换和每个校验特性。信息均为 7.6.10 的真实输出。
命令参考
| 语法 | 用途 | 说明 |
|---|---|---|
[ValidateSet('a','b')] | 固定列表 + 补全 | 需要精确大小写时用 IgnoreCase = $false |
[ValidatePattern('re', ErrorMessage = '…{0}…')] | 正则 | 用 ^…$ 锚定 |
[ValidateRange(1, 65535)] | 数值范围 | 或者类别:'Positive' |
[ValidateScript({ … }, ErrorMessage = '…')] | 任意规则 | $_ 是值 |
[ValidateNotNullOrEmpty()] / [ValidateNotNullOrWhiteSpace()] | 非空 | 后者需要 7.4+ |
[ArgumentCompleter({ param($c,$p,$w,$a,$f) … })] | 动态补全 | 返回字符串或 CompletionResult |
Register-ArgumentCompleter -CommandName C -ParameterName P -ScriptBlock { … } | 从外部添加补全 | 对整个会话生效;放在模块或配置文件中 |
TabExpansion2 -inputScript 'cmd -P ' -cursorColumn N | 在脚本中测试补全 | .CompletionMatches |
function Get-Srv {
[CmdletBinding()]
param(
[ValidateSet('dev', 'staging', 'prod')] [string]$Env = 'dev',
[ValidateSet('web', 'api', 'db', IgnoreCase = $false)] [string]$Role = 'web'
)
"env=$Env role=$Role"
}
Get-Srv -Env PROD
Get-Srv -Env qa
Get-Srv -Role WEB
env=PROD role=web Get-Srv: Cannot validate argument on parameter 'Env'. The argument "qa" does not belong to the set "dev,staging,prod" specified by the ValidateSet attribute. Supply an argument that is in the set and then try the command again. Get-Srv: Cannot validate argument on parameter 'Role'. The argument "WEB" does not belong to the set "web,api,db" specified by the ValidateSet attribute. Supply an argument that is in the set and then try the command again.
function New-ServerName {
[CmdletBinding()]
param(
[ValidatePattern('^[a-z]+-\d{2}$', ErrorMessage = "'{0}' is not a valid server name (expected e.g. web-03)")]
[string]$Name
)
"ok: $Name"
}
New-ServerName web-03
New-ServerName Web_3
function New-ServerName2 { [CmdletBinding()] param([ValidatePattern('^[a-z]+-\d{2}$')] [string]$Name) "ok: $Name" }
New-ServerName2 Web_3
ok: web-03
New-ServerName: Cannot validate argument on parameter 'Name'. 'Web_3' is not a valid server name (expected e.g. web-03)
New-ServerName2: Cannot validate argument on parameter 'Name'. The argument "Web_3" does not match the "^[a-z]+-\d{2}$" pattern. Supply an argument that matches "^[a-z]+-\d{2}$" and try the command again.
function Set-Timeout {
[CmdletBinding()]
param(
[ValidateRange(1, 60)] [int]$Seconds = 5,
[ValidateRange('Positive')] [int]$Retries = 3
)
"timeout=$Seconds retries=$Retries"
}
Set-Timeout -Seconds 0
Set-Timeout -Retries 0
Set-Timeout -Seconds 30 -Retries 2
Set-Timeout: Cannot validate argument on parameter 'Seconds'. The 0 argument is less than the minimum allowed range of 1. Supply an argument that is greater than or equal to 1 and then try the command again. Set-Timeout: Cannot validate argument on parameter 'Retries'. The argument "0" cannot be validated because its value is not greater than zero. timeout=30 retries=2
function Import-Inventory {
[CmdletBinding()]
param(
[ValidateScript({ Test-Path -LiteralPath $_ -PathType Leaf }, ErrorMessage = 'File not found: {0}')]
[string]$Path
)
"importing $Path"
}
Import-Inventory -Path ~/pslab/data/inventory.json
Import-Inventory -Path ~/pslab/data/nope.json
importing ~/pslab/data/inventory.json Import-Inventory: Cannot validate argument on parameter 'Path'. File not found: ~/pslab/data/nope.json
function Send-Report {
[CmdletBinding()]
param(
[ValidateNotNullOrEmpty()] [string]$To,
[ValidateNotNullOrWhiteSpace()] [string]$Subject = 'report',
[ValidateCount(1, 3)] [string[]]$Cc = @('ops@example.com'),
[ValidateLength(1, 10)] [string]$Tag = 'daily'
)
"to=$To subject=$Subject cc=$($Cc.Count) tag=$Tag"
}
Send-Report -To ''
Send-Report -To a@example.com -Subject ' '
Send-Report -To a@example.com -Cc a, b, c, d
Send-Report -To a@example.com -Tag 'much-too-long'
Send-Report -To a@example.com
Send-Report: Cannot validate argument on parameter 'To'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again. Send-Report: Cannot validate argument on parameter 'Subject'. The argument is null, empty, or consists of only white-space characters. Provide an argument that contains non white-space characters, and then try the command again. Send-Report: Cannot validate argument on parameter 'Cc'. The parameter requires at least 1 value(s) and no more than 3 value(s) - 4 value(s) were provided. Send-Report: Cannot validate argument on parameter 'Tag'. The character length of the 13 argument is too long. Shorten the character length of the argument so it is fewer than or equal to "10" characters, and then try the command again. to=a@example.com subject=report cc=1 tag=daily
如何验证:每条信息都以 Cannot validate argument on parameter 'X' 开头,错误 ID 是 ParameterArgumentValidationError($Error[0].FullyQualifiedErrorId)。常见错误:没有锚定的模式,例如 '[a-z]+-\d{2}',也会接受 xx web-01 yy。生产用法:在每个会修改东西的函数里校验环境名、端口、数量和路径。
目标:探查校验的边界,并构建三种补全,用 TabExpansion2 测试。环境:pwsh 7.6,已加载 OpsKit(完成模块 8 后执行 . ~/pslab/OpsKit/OpsKit.ps1,或直接使用清单文件)。费用:无。
function Get-Default { [CmdletBinding()] param([ValidateRange(1, 10)] [int]$N = 99) "N=$N" }
Get-Default
function Set-Limit {
[CmdletBinding()]
param([ValidateRange(1, 10)] [int]$Limit = 5)
$Limit = $Limit * 3
"limit=$Limit"
}
Set-Limit -Limit 2
Set-Limit -Limit 4
N=99 limit=6 Set-Limit: The variable cannot be validated because the value 12 is not a valid value for the Limit variable.
教训:不要拿带校验的参数变量存放中间值;用一个新变量($effective = $Limit * 3)。
(TabExpansion2 -inputScript 'Get-OpsServer -Env ' -cursorColumn 19).CompletionMatches.CompletionText -join ' ' (TabExpansion2 -inputScript 'Get-OpsServer -Env p' -cursorColumn 20).CompletionMatches.CompletionText -join ' '
dev prod staging prod
function Get-OpsRegion {
[CmdletBinding()]
param(
[ArgumentCompleter({
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)
(Get-OpsServer).Region | Sort-Object -Unique | Where-Object { $_ -like "$wordToComplete*" }
})]
[string]$Region
)
Get-OpsServer | Where-Object Region -eq $Region | Select-Object -ExpandProperty Name
}
(TabExpansion2 -inputScript 'Get-OpsRegion -Region ' -cursorColumn 22).CompletionMatches.CompletionText -join ' '
(TabExpansion2 -inputScript 'Get-OpsRegion -Region ca-' -cursorColumn 25).CompletionMatches.CompletionText -join ' '
Get-OpsRegion -Region eastus
ca-central-1 canadacentral ca-central-1
最后一个调用什么都不返回,也不报错:补全器只给建议,不做校验。
function Get-Log { [CmdletBinding()] param([ArgumentCompletions('access.log', 'error.log')] [string]$File) "file=$File" }
(TabExpansion2 -inputScript 'Get-Log -File ' -cursorColumn 14).CompletionMatches.CompletionText -join ' '
Get-Log -File other.log
access.log error.log file=other.log
Register-ArgumentCompleter -CommandName Test-OpsEndpoint -ParameterName Target -ScriptBlock {
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)
Get-OpsServer | Where-Object IP -like "$wordToComplete*" | ForEach-Object {
[System.Management.Automation.CompletionResult]::new($_.IP, $_.IP, 'ParameterValue', "$($_.Name) ($($_.Env))")
}
}
(TabExpansion2 -inputScript 'Test-OpsEndpoint -Target 10.30.1.' -cursorColumn 33).CompletionMatches |
Format-Table CompletionText, ToolTip -AutoSize
Register-ArgumentCompleter -CommandName Get-OpsServer -ParameterName Name -ScriptBlock {
param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)
$p = @{}; if ($fakeBoundParameters.ContainsKey('Env')) { $p.Env = $fakeBoundParameters.Env }
Get-OpsServer @p | Select-Object -ExpandProperty Name -Unique | Where-Object { $_ -like "$wordToComplete*" }
}
(TabExpansion2 -inputScript 'Get-OpsServer -Env prod -Name ' -cursorColumn 30).CompletionMatches.CompletionText -join ' '
(TabExpansion2 -inputScript 'Get-OpsServer -Env dev -Name ' -cursorColumn 29).CompletionMatches.CompletionText -join ' '
CompletionText ToolTip -------------- ------- 10.30.1.41 web-01 (prod) 10.30.1.42 web-02 (prod) 10.30.1.43 api-01 (prod) 10.30.1.44 db-01 (prod) web-01 web-02 api-01 edge-01 db-01 bastion-01 web-01 api-01 db-01
案例 1:删除了所有备份的备份轮换
问题:有人把配置中的 Keep 清空后,Remove-OldBackup -Keep $cfg.Keep 删除了全部备份:$null 转换为 [int] 是 0,“保留最新的 0 个”。根因:没有校验。修复:[ValidateRange(1, 365)][int]$Keep——调用现在会在任何删除之前失败。第 5 课的 Invoke-OpsBackup 带有这个校验以及 -WhatIf。
案例 2:一条难懂的错误信息耗掉了一个小时
问题:运维人员不断报告 VM 名称出现 “The " $_ -match '^(?=.{3,15}$)[a-z][a-z0-9-]*$' " validation script … did not return a result of True”。修复:ErrorMessage = "VM name '{0}' must be 3-15 chars, lowercase letters, digits and dashes"。校验信息就是用户界面。
案例 3:让控制台卡住的补全器
问题:一个补全器在每次按 Tab 时都调用云 API;网络慢时控制台卡住好几秒。修复:把结果缓存在带时间戳的 $script: 变量中(模块 2),让补全器保持本地、快速,并且绝不修改状态。
常见错误与修复
Cannot validate argument on parameter 'X'. …
原因:值未通过某个 Validate* 特性。信息的后半部分会告诉你是哪一个。
(Get-Command f).Parameters['X'].Attributes | Select-Object TypeId
The variable cannot be validated because the value … is not a valid value for the X variable.
原因:函数体给带校验的参数变量赋了新值。
修复:使用单独的变量。
Tab 补全显示的是文件名而不是我的值
原因:补全器抛出了异常或什么都没返回,PowerShell 退回到路径补全;或者 Register-ArgumentCompleter 的命令名/参数名写错了。
修复:通过 TabExpansion2 运行补全器,并查看 $Error[0]。
1. 添加一个端口参数,接受 1–65535,并补全 80、443 和 8080。
[ArgumentCompletions(80, 443, 8080)] [ValidateRange(1, 65535)] [int]$Port = 8080
2. 打印一次校验失败的错误 ID。
try { Get-OpsServer -Env qa -ErrorAction Stop } catch { $_.FullyQualifiedErrorId }
# ParameterArgumentValidationError,Get-OpsServerGet-OpsServer -Env 应该用 ValidateSet,还是用一个从 opskit.config.psd1 读取环境的补全器?
需要权衡。ValidateSet 一行就同时提供校验和补全,但列表是硬编码的,必须随配置一起修改。补全器读取真实列表,但不做校验,所以你还需要一个使用同样查找逻辑的 ValidateScript。v0.1 中三个环境很稳定,所以 ValidateSet 胜出;列表很长或经常变化(区域、订阅)时,应使用补全器 + 脚本校验,或实现 IValidateSetValuesGenerator 的类。
已验证的教学视频
官方文档
- about_Functions_Advanced_Parameters(校验特性)· about_Functions_Argument_Completion · Register-ArgumentCompleter
视频分镜(约 90 秒)
画面:类型转换器后面有一道安检门;'qa' 被 ValidateSet 守卫拦下,并打印出原因。
旁白:校验在你的代码之前运行,并给出准确的信息。
画面:一个默认值绕过了安检门;函数体内的一次赋值被再次检查。
旁白:默认值被信任;重新赋值不被信任。
画面:按下 Tab,弹出来自清单的建议。
旁白:补全器负责建议;校验器负责裁决。
模块 6 · 管道输入:ValueFromPipeline(ByPropertyName) 与 begin / process / end
process,再给参数加上真实对象所带的属性名作为别名- 用
ValueFromPipeline(整个对象,按类型)和ValueFromPipelineByPropertyName(与参数名或别名同名的属性)声明管道参数。 - 解释 begin / process / end,并复现经典 bug:没有
process块 → 只处理最后一个管道对象。 - 用
[string[]]+process中的foreach同时支持-Target a, b和'a','b' | …。 - 用
[Alias('IP', 'ComputerName')]让Import-Csv servers.csv的行和Get-OpsServer的对象都能绑定,识别类型转换陷阱(把@{Name=…}当成主机名),并用Trace-Command证明绑定过程。
是什么:三个块,两种接收对象的方式
function Test-Target {
[CmdletBinding()]
param(
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[Alias('IP', 'ComputerName')]
[string]$Target
)
begin { } # once, before the first object (pipeline params NOT bound yet)
process { "Target=[$Target]" } # once per pipeline object (or once if no pipeline input)
end { } # once, after the last object
}
| 特性 | 绑定什么 | 输入示例 |
|---|---|---|
ValueFromPipeline | 整个对象,前提是它是(或能转换成)参数类型 | '10.30.1.41' | Test-Target |
ValueFromPipelineByPropertyName | 与参数名或其某个别名同名的属性值 | Import-Csv servers.csv | Test-Target(属性 IP) |
为什么:没有 process 的函数只看到最后一个对象
没有命名块的函数体就是一个 end 块。绑定器仍会把每个传入对象依次绑定到 $Item——一个接一个地覆盖——然后才运行 end,而它看到的是最后一个值。结果:'web-01','api-01','db-01' | Show-Item 只打印 got db-01,而且没有任何错误。在 begin 中,管道参数还没有绑定(为空);在 end 中,它们仍保存着最后一个对象。
怎么做:绑定器顺序同样适用于你的参数
和第 1 课一样,对每个对象,绑定器依次尝试:不转换的 ByValue → 不转换的 ByPropertyName → 带转换的 ByValue → 带转换的 ByPropertyName。这对带 ValueFromPipeline 的 [string] 参数有一个尖锐的后果:任何对象都能转换成字符串。如果没有属性名或别名匹配,一行 CSV 会被绑定成文本 @{Name=web-01; Env=dev; …}。有了 [Alias('IP')],第 2 步的 ByPropertyName 就会在第 3 步的转换被尝试之前成功。
| 管道中的对象 | 没有别名 | 有 [Alias('IP','ComputerName')] |
|---|---|---|
'10.30.1.41' | ByValue → 10.30.1.41 | ByValue → 10.30.1.41 |
CSV 行(有 IP) | 带转换的 ByValue → @{Name=web-01; Env=dev; …} ✗ | ByPropertyName IP → 10.10.1.21 ✓ |
[pscustomobject]@{ComputerName='build-07'} | @{ComputerName=build-07} ✗ | build-07 ✓ |
| 没有任何匹配名称的对象 | 两种情况下都被转换成 @{…} 文本——[string] 的 ByValue 参数什么都接受 | |
何时:ByValue、ByPropertyName 还是两者都要?
- 对象以属性形式携带的标识符(
IP、Name、Port、Path)用 ByPropertyName——这让你的命令能与其他命令组合。 - 调用方会通过管道传入普通字符串时,在
[string]上用 ByValue;并接受不相关的对象会被转换这一事实。在具体类型([PSTypeName('OpsKit.Server')],模块 7)上,ByValue 是严格的。 - 只有在真正需要全部对象时(排序、汇总)才在
process中收集、在end中计算——这会让你的函数变成像Sort-Object一样的阻塞阶段。
process 调用收到一个对象。② “没有 process 也能拿到所有对象”——你只拿到最后一个。③ “$Target 在 begin 中可用”——来自管道的值不可用。④ “属性不匹配时调用会失败”——对于 [string] 的 ByValue 参数,对象会被转换成文本。⑤ “$input 是现代写法”——它是简单函数的自动枚举器;高级函数应使用管道参数。图解:一行 CSV 进入 Test-Target
图解:begin / process / end 的时间线
核心动画:绑定到你自己的函数
选择管道中的对象以及函数的写法,然后逐步观察绑定器和各个块。绿色 = 已绑定/已处理,黄色 = 尝试后跳过,红色 = 结果错误或失败。所有结果都在 PowerShell 7.6.10 上复现;绑定细节来自 Trace-Command -Name ParameterBinding。
[string] 参数,跟踪输出显示 Parameter [Target] PIPELINE INPUT ValueFromPipeline NO COERCION → BIND arg [@{Name=web-01; …}] to param [Target] SKIPPED,接着 Parameter [Target] PIPELINE INPUT ValueFromPipelineByPropertyName NO COERCION → BIND arg [10.10.1.21] to param [Target] SUCCESSFUL。完整跟踪见“命令”分页。命令参考
| 语法 | 用途 | 说明 |
|---|---|---|
[Parameter(ValueFromPipeline)] | 绑定整个对象 | 按类型,然后带转换 |
[Parameter(ValueFromPipelineByPropertyName)] | 绑定一个属性 | 名称或别名必须匹配 |
[Alias('IP','ComputerName')] | 额外可绑定的属性名 | 也可作为参数名使用 |
begin {} process {} end {} | 生命周期 | 没有块的函数体 = end |
process { foreach ($t in $Target) { … } } | 处理两种来源的数组 | 配合 [string[]]$Target |
$input | 简单函数中管道输入的枚举器 | 高级函数中避免使用 |
Trace-Command -Name ParameterBinding -PSHost -Expression { … } | 证明绑定 | 阅读 BIND PIPELINE 部分 |
function Show-Item {
[CmdletBinding()]
param([Parameter(ValueFromPipeline)] [string]$Item)
"got $Item" # no process block → this is the end block
}
'web-01', 'api-01', 'db-01' | Show-Item
function Show-Item {
[CmdletBinding()]
param([Parameter(ValueFromPipeline)] [string]$Item)
process { "got $Item" }
}
'web-01', 'api-01', 'db-01' | Show-Item
got db-01 got web-01 got api-01 got db-01
function Measure-Item {
[CmdletBinding()]
param([Parameter(ValueFromPipeline)] [string]$Item)
begin { Write-Host "begin: Item=[$Item]"; $n = 0 }
process { $n++; Write-Host "process: Item=[$Item]" }
end { Write-Host "end: Item=[$Item]"; "total $n" }
}
'web-01', 'api-01' | Measure-Item
begin: Item=[] process: Item=[web-01] process: Item=[api-01] end: Item=[api-01] total 2
function Show-Item {
[CmdletBinding()]
param([Parameter(Mandatory, ValueFromPipeline)] [string[]]$Item)
process { foreach ($i in $Item) { "got $i" } }
}
Show-Item -Item web-01, api-01
'web-01', 'api-01' | Show-Item
function Show-ItemBug {
[CmdletBinding()]
param([Parameter(Mandatory, ValueFromPipeline)] [string[]]$Item)
process { "got $Item" } # forgot the foreach
}
Show-ItemBug -Item web-01, api-01
got web-01 got api-01 got web-01 got api-01 got web-01 api-01
如何验证:两种方式都调用一下函数——通过实参和通过管道——并比较结果。常见错误:只测试管道形式;用数组实参调用时,process 只运行一次,拿到整个数组。生产用法:OpsKit 中所有接收目标的函数要么遵循 [string[]] + foreach 模式,要么像 Test-OpsEndpoint 那样使用一次只接收一个对象的标量参数。
function Get-Endpoint {
[CmdletBinding()]
param(
[Parameter(Mandatory, ValueFromPipelineByPropertyName)] [string]$IP,
[Parameter(ValueFromPipelineByPropertyName)] [int]$Port = 80
)
process { "{0}:{1}" -f $IP, $Port }
}
Import-Csv ~/pslab/data/servers.csv | Select-Object -First 2 | Get-Endpoint
Get-Content ~/pslab/data/inventory.json -Raw | ConvertFrom-Json | Select-Object -First 2 | Get-Endpoint
'10.10.1.21' | Get-Endpoint
10.10.1.21:80 10.10.1.22:80 10.10.1.21:8080 10.10.1.22:8080 Get-Endpoint: The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.
CSV 没有 Port 列,所以每一行都使用默认值 80;JSON 清单有 Port: 8080,会按属性名绑定。普通字符串没有 IP 属性,而 -IP 没有 ByValue——这和第 1 课中 'pwsh' | Get-Process 的错误是一回事。
Trace-Command -Name ParameterBinding -PSHost -Expression {
Import-Csv ~/pslab/data/servers.csv | Select-Object -First 1 | Test-Target
}
BIND NAMED cmd line args [Test-Target]
BIND POSITIONAL cmd line args [Test-Target]
MANDATORY PARAMETER CHECK on cmdlet [Test-Target]
CALLING BeginProcessing
CALLING BeginProcessing
CALLING BeginProcessing
CALLING ProcessRecord
…
BIND PIPELINE object to parameters: [Test-Target]
PIPELINE object TYPE = [Selected.System.Management.Automation.PSCustomObject]
RESTORING pipeline parameter's original values
Parameter [Target] PIPELINE INPUT ValueFromPipeline NO COERCION
BIND arg [@{Name=web-01; Env=dev; Region=canadacentral; IP=10.10.1.21; Role=web; Monitored=true}] to parameter [Target]
Executing DATA GENERATION metadata: [System.Management.Automation.ArgumentTypeConverterAttribute]
BIND arg [@{Name=web-01; Env=dev; Region=canadacentral; IP=10.10.1.21; Role=web; Monitored=true}] to param [Target] SKIPPED
Parameter [Target] PIPELINE INPUT ValueFromPipelineByPropertyName NO COERCION
BIND arg [10.10.1.21] to parameter [Target]
BIND arg [10.10.1.21] to param [Target] SUCCESSFUL
MANDATORY PARAMETER CHECK on cmdlet [Test-Target]
CALLING ProcessRecord
CALLING EndProcessing
Target=[10.10.1.21]
目标:让 servers.csv 的行和普通字符串都能绑定到 -Target,然后复现三个经典的管道 bug。环境:~/pslab 中的 pwsh 7.6。费用:无。
function Test-Target {
[CmdletBinding()]
param([Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [string]$Target)
process { "Target=[$Target]" }
}
'10.30.1.41' | Test-Target
Import-Csv ~/pslab/data/servers.csv | Select-Object -First 1 | Test-Target
Target=[10.30.1.41]
Target=[@{Name=web-01; Env=dev; Region=canadacentral; IP=10.10.1.21; Role=web; Monitored=true}]function Test-Target {
[CmdletBinding()]
param(
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[Alias('IP', 'ComputerName')]
[string]$Target
)
process { "Target=[$Target]" }
}
'10.30.1.41' | Test-Target
Import-Csv ~/pslab/data/servers.csv | Select-Object -First 1 | Test-Target
[pscustomobject]@{ ComputerName = 'build-07' } | Test-Target
Target=[10.30.1.41] Target=[10.10.1.21] Target=[build-07]
@([pscustomobject]@{ IP = '10.0.0.1' }, [pscustomobject]@{ Name = 'no-ip' }, [pscustomobject]@{ IP = '10.0.0.3' }) | Test-Target
Target=[10.0.0.1]
Target=[@{Name=no-ip}]
Target=[10.0.0.3]
如果这不可接受,就去掉 ValueFromPipeline(只保留 ByPropertyName)——此时字符串必须通过 -Target 传入——或用 [ValidatePattern()]/[ValidateScript()] 校验。
Show-Item(只有 got db-01)。Bug 2——忘了 foreach:Show-ItemBug -Item web-01, api-01 只打印一行 got web-01 api-01。Bug 3——同一参数既有实参又有管道:
'10.30.1.41' | Test-Target -Target 10.0.0.1
Test-Target: The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.
在命令行上绑定过的参数,不再接受管道输入。
Select-Object -First 可以提前停止它:
function Write-Slow { [CmdletBinding()] param([Parameter(ValueFromPipeline)] $InputObject) process { Write-Host " emit $InputObject"; $InputObject } }
1..3 | Write-Slow | Select-Object -First 1
emit 1 1
Sort-Object 一样的阻塞阶段):
function Get-Sorted {
[CmdletBinding()]
param([Parameter(ValueFromPipeline)] [string]$Name)
begin { $all = [System.Collections.Generic.List[string]]::new() }
process { $all.Add($Name) }
end { $all | Sort-Object -Unique }
}
(Get-Content ~/pslab/data/inventory.json -Raw | ConvertFrom-Json).Name | Get-Sorted
api-01 bastion-01 db-01 edge-01 web-01 web-02
Trace-Command 示例,找到 SKIPPED 那一行以及紧随其后的 BIND arg [10.10.1.21] … SUCCESSFUL。案例 1:只列出最后一台服务器的补丁报告
问题:对一个 300 行的文件执行 Get-Content servers.txt | Get-PatchLevel,只返回了一行。根因:Get-PatchLevel 有管道参数但没有 process 块;函数体作为 end 只运行了一次,拿到最后一个名字。没有报错,所以几周都没被发现。修复:把函数体包进 process { }。预防:写一个测试,通过管道传入三个对象并期望得到三个结果(第 8 课)。
案例 2:主机名为“@{Name=…}”的 DNS 错误
问题:一个连通性脚本记录了成千上万条“No such host is known: @{Name=web-01; Env=prod; IP=…}”。根因:CMDB 导出把 ComputerName 列改名成了 IP;函数的 [string]$ComputerName 带有 ValueFromPipeline,于是绑定器退回到类型转换。修复:[Alias('IP', 'HostName')];并在 verbose 输出中记录绑定到的目标,这样问题会立即显现。
案例 3:把 200 万个对象全部加载进内存的管道函数
问题:一个日志增强函数“为了效率”在 begin/process 中收集所有输入,在 end 中处理。内存不断增长,直到作业被杀掉。修复:在 process 中完成逐对象的工作并立即输出;只在 end 中做汇总(计数、求和)。
常见错误与修复
只处理了最后一个管道对象
原因:没有 process 块。
修复:process { … };用 1..3 | f 检查。
The input object cannot be bound to any parameters for the command …
原因:没有参数能按 ByValue 接受这个对象,它的属性名也不匹配任何 ByPropertyName 参数或别名——或者该参数已经在命令行上给出。
$obj | Get-Member -MemberType Properties
(Get-Command f).Parameters.Values | Where-Object { $_.Attributes.ValueFromPipelineByPropertyName -contains $true } | Select-Object Name, Aliases参数收到的是 @{Name=…; IP=…} 这样的文本
原因:[string] 参数上带转换的 ByValue。
修复:把属性名加为 [Alias()],或去掉 ValueFromPipeline。
参数在 begin 中为空
原因:管道值在 begin 之后才逐个对象绑定。
修复:把代码移到 process;begin 只做不需要输入的准备工作。
1. 列出你的 Test-Target 中支持管道的参数及其别名。
(Get-Command Test-Target).Parameters.Values |
Where-Object { $_.Attributes.ValueFromPipeline -contains $true -or $_.Attributes.ValueFromPipelineByPropertyName -contains $true } |
Select-Object Name, Aliases2. 编写 Measure-Bytes,对管道传入文件的 Length 求和并输出一个总数。
function Measure-Bytes {
[CmdletBinding()]
param([Parameter(Mandatory, ValueFromPipelineByPropertyName)] [long]$Length)
begin { $sum = 0 }
process { $sum += $Length }
end { $sum }
}
Get-ChildItem ~/pslab/data -File | Measure-BytesTest-OpsEndpoint 的 -Target 同时声明了 ValueFromPipeline 和 ByPropertyName,-Port 只声明了 ByPropertyName。传入 [pscustomobject]@{ IP = '127.0.0.1'; Port = 18080 } 时会怎样?传入字符串 '127.0.0.1' 呢?
对象:-Target 的 ByValue 被跳过(不转换时它不是字符串),ByPropertyName 把 IP 绑定到 -Target,把 Port 绑定到 -Port。字符串:ByValue 把它绑定到 -Target;-Port 保持默认值 8080。两种情况都在模块 8 和验收检查“pipeline binds IP+Port”中得到验证。
已验证的教学视频
官方文档
- about_Functions_Advanced_Parameters(ValueFromPipeline…)· about_Functions_Advanced_Methods(begin/process/end)· about_Pipelines
视频分镜(约 90 秒)
画面:第 1 课的绑定器守卫现在站在你的函数门口;一行 CSV 出示它的 IP 徽章,守卫核对别名列表。
旁白:声明哪些参数接受管道输入——以及哪些属性名算数。
画面:三个包裹到达,但没有 process 工位,只拆开了最后一个。
旁白:逐对象的工作属于 process。
画面:一个没有 IP 徽章的包裹被压扁成文本标签“@{…}”。
旁白:字符串参数什么都接受;别名让正确的属性先胜出。
模块 7 · 输出与帮助:[OutputType]、PSTypeName、基于注释的帮助与展开传参
Get-Help 找得到的地方,并用展开传参传递参数- 声明
[OutputType()],并知道它只是元数据(不强制执行)。 - 给对象一个 PSTypeName,在
Get-Member和PSObject.TypeNames中看到它,用Update-TypeData改变默认显示,并用[PSTypeName('OpsKit.Server')]只接受这种对象。 - 编写基于注释的帮助并把它放在
Get-Help找得到的位置(已验证的放置规则),包含.PARAMETER和.EXAMPLE段落。 - 使用展开传参(
@params哈希表和数组)、显式覆盖、带.Remove()的@PSBoundParameters转发,并选择批准的动词(Get-Verb)。
是什么:三种“契约”元数据
| 机制 | 效果 | 是否强制? |
|---|---|---|
[OutputType('OpsKit.Server')] | 由 Get-Command(.OutputType)和帮助显示;工具和补全会对 .NET 类型使用它 | 否——声明了 [int] 的函数照样可以输出字符串 |
[pscustomobject]@{…} 中的 PSTypeName = 'OpsKit.Server' | 作为第一项插入 PSObject.TypeNames;Get-Member 显示 TypeName: OpsKit.Server;类型数据和格式视图可以针对它 | 它就是对象的身份 |
参数上的 [PSTypeName('OpsKit.Server')]$Server | 只接受 TypeNames 中包含该名称的对象 | 是,由绑定器强制 |
为什么:帮助和类型名让工具可被发现
你的函数的使用者会用与内置 cmdlet 相同的发现流程(第 1 课模块 3):Get-Help Get-OpsServer -Examples、Get-Command -Syntax、| Get-Member。函数的帮助来自基于注释的帮助——不需要 Update-Help。类型名让你可以添加整洁的默认视图(第 4 课会附带 .format.ps1xml;这里先用 Update-TypeData),也让其他函数可以要求“一个服务器对象,而不是任意对象”。
怎么做:基于注释的帮助必须放在哪里(已验证)
| 位置 | 7.6.10 上的 Get-Help |
|---|---|
紧贴 function 上方(没有空行) | ✓ 找到 |
在 function 上方,中间隔一个空行 | ✓ 找到 |
| 在上方,中间隔两个空行 | ✗ 被忽略(只显示名称) |
| 函数体内的第一项(OpsKit 的写法) | ✓ 找到 |
在函数体内,但位于 [CmdletBinding()] param() 之后 | ✗ 被忽略(显示语法) |
| 函数体内的最后一项 | ✓ 找到 |
对于脚本,第 1 课找到了对应的规则:帮助块必须位于 #Requires 之前。关键字拼写很重要(.SYNOPSIS、.DESCRIPTION、.PARAMETER Name、.EXAMPLE、.OUTPUTS);一个未知关键字会让整个块失效。
何时:展开传参与转发
展开传参把哈希表作为命名参数(Get-OpsServer @p),或把数组作为位置参数传入。它让长调用更易读,可以按条件构建参数(if ($Role) { $p.Role = $Role }),而且在 7.x 中,写在展开之后的显式参数会覆盖展开的值。@PSBoundParameters 把调用方传入的内容(包括 -Verbose)原样转发给内部命令——要先删除内部命令不具备的键,否则会以 “A parameter cannot be found …” 失败。
[OutputType] 会转换或检查输出”——它只是文档。② “用 $p 就能展开传参”——Get-OpsServer $p 把哈希表作为一个位置值传入;你需要 @p。③ “帮助可以放在函数里任何地方”——不能放在 param() 之后。④ “Select-Object -First 1 返回同一个对象”——对于 [pscustomobject],它会在前面加上类型名 Selected.System.Management.Automation.PSCustomObject(已在 7.6.10 上验证),检查 TypeNames[0] 的代码就会出错;请用 -contains 检查。⑤ “随便用什么动词都行”——未批准的动词会在导入时产生警告,并妨碍命令发现。图解:一个对象,多个读取其类型名的使用者
图解:展开传参与转发
帮助块位置检查器(及其他契约检查)
选择一种放置方式或一个调用,逐步观察 PowerShell 如何找到帮助、匹配类型名或展开参数。结果在 7.6.10 上复现。
命令参考
| 语法 | 用途 | 说明 |
|---|---|---|
[OutputType('Type.Name', ParameterSetName = 'X')] | 按参数集声明输出 | 可以写多个 |
[pscustomobject]@{ PSTypeName = 'OpsKit.Server'; … } | 为对象的类型命名 | 像键一样写在开头,但不是属性 |
$o.PSObject.TypeNames / $o.pstypenames | 查看类型名 | 最具体的在前 |
Update-TypeData -TypeName T -DefaultDisplayPropertySet a, b | 类型的默认列 | 仅对会话有效;第 4 课用文件 |
[PSTypeName('T')]$p | 只接受类型名为 T 的对象 | 也适用于管道输入 |
<# .SYNOPSIS … .PARAMETER X … .EXAMPLE … #> | 基于注释的帮助 | 见放置规则表 |
Get-Help f -Examples / -Parameter X / -Full | 阅读帮助 | 离线可用 |
cmd @hash、cmd @array | 展开传参 | 显式参数覆盖展开的值 |
inner @PSBoundParameters | 转发调用方的参数 | 用 .Remove('X') 删除内部命令没有的 |
Get-Verb、Get-Verb -Verb Fetch | 批准的动词 | 7.6 中有 100 个;未批准的动词查不到 |
. ~/pslab/OpsKit/OpsKit.ps1
(Get-Command Get-OpsServer).OutputType.Name
(Get-Command Get-OpsConfig).OutputType | Format-Table Name, Type -AutoSize
function Get-Number { [CmdletBinding()] [OutputType([int])] param() 'not a number' }
(Get-Number).GetType().Name
OpsKit.Server Name Type ---- ---- OpsKit.EnvConfig System.Collections.Hashtable System.Collections.Hashtable String
$s = Get-OpsServer -Env prod -Name edge-01 $s.PSObject.TypeNames Get-OpsServer -Env dev | Get-Member -MemberType NoteProperty
OpsKit.Server System.Management.Automation.PSCustomObject System.Object TypeName: OpsKit.Server Name MemberType Definition ---- ---------- ---------- Env NoteProperty string Env=dev IP NoteProperty string IP=10.10.1.21 Monitored NoteProperty bool Monitored=True Name NoteProperty string Name=web-01 Port NoteProperty int Port=8080 Region NoteProperty string Region=canadacentral Role NoteProperty string[] Role=System.String[]
Get-OpsServer -Env dev | Format-Table Update-TypeData -TypeName OpsKit.Server -DefaultDisplayPropertySet Name, Env, Role, IP -Force Get-OpsServer -Env dev
Name Env Role IP Port Region Monitored
---- --- ---- -- ---- ------ ---------
web-01 dev {web} 10.10.1.21 8080 canadacentral True
api-01 dev {api} 10.10.1.22 8080 canadacentral True
db-01 dev {db} 10.10.1.23 8080 canadacentral False
Name Env Role IP
---- --- ---- --
web-01 dev {web} 10.10.1.21
api-01 dev {api} 10.10.1.22
db-01 dev {db} 10.10.1.23
如何验证:没有类型数据时,7 个属性以列表显示(第 1 课:5 个及以上属性 → 列表);有了 4 个属性的默认显示集,它们以表格显示,而 Format-List * 仍然显示全部。常见错误:为了好看在函数内部使用 Format-Table——这会毁掉对象。生产用法:第 4 课把它移到由模块清单加载的 OpsKit.format.ps1xml/types.ps1xml 中。
function Show-Server {
[CmdletBinding()]
param([Parameter(Mandatory, ValueFromPipeline)] [PSTypeName('OpsKit.Server')] $Server)
process { "{0} ({1}) at {2}" -f $Server.Name, $Server.Env, $Server.IP }
}
Get-OpsServer -Env staging | Show-Server
Import-Csv ~/pslab/data/servers.csv | Select-Object -First 1 | Show-Server
$first = Get-OpsServer -Env dev | Select-Object -First 1
$first.PSObject.TypeNames
$first | Show-Server
$first.PSObject.TypeNames -contains 'OpsKit.Server'
web-01 (staging) at 10.20.1.31 api-01 (staging) at 10.20.1.32 db-01 (staging) at 10.20.1.33 Show-Server: The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input. Selected.System.Management.Automation.PSCustomObject OpsKit.Server System.Management.Automation.PSCustomObject System.Object web-01 (dev) at 10.10.1.21 True
$p = @{
Env = 'prod'
Role = 'web'
}
Get-OpsServer @p | Select-Object -ExpandProperty Name
Get-OpsServer @p -Role api | Select-Object -ExpandProperty Name # explicit wins
$positional = @('prod')
Get-OpsServer @positional -Role db | Select-Object -ExpandProperty IP
Get-OpsServer $p
Get-OpsServer @p -Port 22
web-01 web-02 edge-01 api-01 edge-01 10.30.1.44 Get-OpsServer: Cannot validate argument on parameter 'Env'. The argument "System.Collections.Hashtable" does not belong to the set "dev,staging,prod" specified by the ValidateSet attribute. Supply an argument that is in the set and then try the command again. Get-OpsServer: A parameter cannot be found that matches parameter name 'Port'.
目标:亲自验证帮助块的放置规则,阅读 OpsKit 的帮助,并编写一个转发包装函数。环境:pwsh 7.6,模块 8 中的 OpsKit(如果你愿意,可以先做模块 8)。费用:无。
~/pslab/scripts/help-test.ps1:
<#
.SYNOPSIS
Help directly above the function (no blank line).
#>
function Get-HelpAbove { 'x' }
<#
.SYNOPSIS
Help with ONE blank line before the function.
#>
function Get-HelpOneBlank { 'x' }
<#
.SYNOPSIS
Help with TWO blank lines before the function.
#>
function Get-HelpTwoBlank { 'x' }
function Get-HelpInside {
<#
.SYNOPSIS
Help as the first thing inside the body.
#>
'x'
}
function Get-HelpAfterAttr {
[CmdletBinding()]
param()
<#
.SYNOPSIS
Help after param() - not the start of the body.
#>
'x'
}
function Get-HelpAtEnd {
'x'
<#
.SYNOPSIS
Help as the last thing in the body.
#>
}
. ~/pslab/scripts/help-test.ps1
'Get-HelpAbove', 'Get-HelpOneBlank', 'Get-HelpTwoBlank', 'Get-HelpInside', 'Get-HelpAfterAttr', 'Get-HelpAtEnd' |
ForEach-Object { '{0,-18} -> {1}' -f $_, (Get-Help $_).Synopsis.Trim() }
Get-HelpAbove -> Help directly above the function (no blank line). Get-HelpOneBlank -> Help with ONE blank line before the function. Get-HelpTwoBlank -> Get-HelpTwoBlank Get-HelpInside -> Help as the first thing inside the body. Get-HelpAfterAttr -> Get-HelpAfterAttr [<CommonParameters>] Get-HelpAtEnd -> Help as the last thing in the body.
Get-Help Get-OpsServer -Parameter Role Get-Help Test-OpsEndpoint -Parameter Target
-Role <String>
A role such as web, api, db or bastion. 'web' also matches the multi-role server edge-01.
Required? false
Position? named
Default value *
Accept pipeline input? false
Aliases
Accept wildcard characters? true
-Target <String>
Host name or IP address. Aliases: IP, ComputerName, HostName.
Required? true
Position? 1
Default value
Accept pipeline input? true (ByValue, ByPropertyName)
Aliases
Accept wildcard characters? false
两个细节:Accept wildcard characters? true 来自 [SupportsWildcards()];而在 7.6.10 上,即使 [Alias()] 能正常工作,函数帮助中的 Aliases 一行仍然是空的——所以别名在 .PARAMETER 文本中又写了一遍。
function Get-OpsProdServer {
[CmdletBinding()]
param([string]$Role = '*', [string]$Name = '*')
Get-OpsServer -Env prod @PSBoundParameters
}
Get-OpsProdServer -Role db | Select-Object Name, Env, IP
Get-OpsProdServer -Role web -Verbose | Select-Object -ExpandProperty Name
Name Env IP ---- --- -- db-01 prod 10.30.1.44 VERBOSE: Reading C:\Users\labadmin\pslab\data\inventory.json web-01 web-02 edge-01
-Verbose 也被转发了(它在 $PSBoundParameters 中),所以内部的 Write-Verbose 被触发。
function Get-OpsWebServer {
[CmdletBinding()]
param([string]$Env, [switch]$Detailed)
Get-OpsServer @PSBoundParameters -Role web
}
Get-OpsWebServer -Env dev -Detailed
function Get-OpsWebServer {
[CmdletBinding()]
param([string]$Env, [switch]$Detailed)
$null = $PSBoundParameters.Remove('Detailed')
$servers = Get-OpsServer @PSBoundParameters -Role web
if ($Detailed) { $servers | Format-List } else { $servers.Name }
}
Get-OpsWebServer -Env prod
Get-OpsWebServer: A parameter cannot be found that matches parameter name 'Detailed'. web-01 web-02 edge-01
Get-Verb -Verb Get, Test, Invoke, Fetch, Check | Format-Table Verb, AliasPrefix, Group -AutoSize
(Get-Verb).Count
Set-Content ~/pslab/tmp/BadVerb.psm1 -Value 'function Fetch-OpsServer { }; function Check-OpsEndpoint { }'
Import-Module ~/pslab/tmp/BadVerb.psm1
Remove-Module BadVerb
Verb AliasPrefix Group ---- ----------- ----- Get g Common Test t Diagnostic Invoke i Lifecycle 100 WARNING: The names of some imported commands from the module 'BadVerb' include unapproved verbs that might make them less discoverable. To find the commands with unapproved verbs, run the Import-Module command again with the Verbose parameter. For a list of approved verbs, type Get-Verb.
案例 1:重构加入 Select-Object 后才失败的检查
问题:编写本课验收脚本时,检查 (Get-OpsServer -Env dev | Select-Object -First 1).PSObject.TypeNames[0] 返回的是 Selected.System.Management.Automation.PSCustomObject,而不是 OpsKit.Server。根因:对 [pscustomobject] 使用 Select-Object,即使只有 -First,也会在前面加上一个 Selected.* 类型名(OpsKit.Server 仍在列表中;同一测试中 Process 和 DirectoryInfo 对象不受影响)。修复:改为对结果取下标(@(Get-OpsServer -Env dev)[0]),并用 -contains 或 [PSTypeName()] 检查类型名,而不是看 [0]。
案例 2:“Get-Help 对我们的模块显示不出有用的东西”
问题:一个团队的函数都有帮助块,但 Get-Help 只显示语法。根因:编码规范要求把帮助块放在 [CmdletBinding()] param() 之后,“这样参数先映入眼帘”。修复:把它移到函数体开头;再加一个 Pester 测试,确保每个导出命令都有摘要(第 8 课)。
案例 3:一个包装函数的 -Verbose 消失在旧函数里
问题:一个高级包装函数把 @PSBoundParameters 转发给一个旧的简单函数。带 -Verbose 调用并没有失败——旧函数悄悄地在 $args 里收到了 -Verbose: True(在 7.6.10 上复现:name=web-01 args=[-Verbose: True])。根因:把哈希表展开传给简单函数无法被检查,因为简单函数什么都接受。修复:把内部函数改成高级函数(这样它就会遵守 -Verbose),或者显式构建参数哈希表。向较旧会话中的命令转发时,对 -ProgressAction(7.4 起才是通用参数)也要同样小心。
常见错误与修复
Get-Help 只显示我的函数的语法
原因:帮助块放错了位置(在 param() 之后,或上方隔了两个空行),或者有无效关键字。
修复:把它移到函数体第一行;对照 about_Comment_Based_Help 检查关键字。
展开传参时传入的值是 “System.Collections.Hashtable”
原因:写成了 $p 而不是 @p。
转发时出现 A parameter cannot be found that matches parameter name 'X'
原因:$PSBoundParameters 中包含内部命令没有的参数。
$null = $PSBoundParameters.Remove('X')我的 [PSTypeName()] 参数拒绝了看起来正确的对象
原因:这些对象被重建过(例如 Import-Csv、ConvertFrom-Json、带属性列表的 Select-Object Name, IP),丢失了类型名。
修复:通过添加类型名的那个函数重新创建它们,或放宽参数类型。
1. 按条件构建参数并展开传入。
$p = @{ Env = 'prod' }
if ($onlyWeb) { $p.Role = 'web' }
Get-OpsServer @p2. 找出所有没有摘要的 OpsKit 函数。
Get-Command -Name *-Ops* -CommandType Function |
Where-Object { (Get-Help $_.Name).Synopsis -match '^\s*\S+-\S+ ' -or -not (Get-Help $_.Name).Synopsis } |
Select-Object -ExpandProperty Name没有帮助时,Synopsis 中是语法行。在 v0.1 中它会找到私有辅助函数 Get-OpsDataPath。
Get-OpsServer 应该自己格式化输出(例如以 | Format-Table 结尾),让用户得到整齐的表格吗?
不应该。Format-Table 把对象变成格式记录;Get-OpsServer | Test-OpsEndpoint 会因此失效。继续输出带类型的对象,用类型数据控制默认视图(现在用 Update-TypeData,第 4 课用格式文件)。用户仍然可以自己在最后管道到 Format-Table。
已验证的教学视频
没有找到专门讲基于注释的帮助放置位置或 PSTypeName 的已验证视频;请使用“实验”中的实验。
官方文档
- about_Comment_Based_Help · about_Functions_OutputTypeAttribute · about_Splatting · Update-TypeData · Everything about PSCustomObject · 批准的动词
视频分镜(约 90 秒)
画面:一个对象戴上名牌“OpsKit.Server”;Get-Member 读出它。
旁白:类型名给你的对象一个身份。
画面:几个帮助块滑向函数;其中一个停在两行之外,掉了下去。
旁白:帮助放在函数体顶部,或紧贴在函数上方。
画面:一个哈希表炸开成命名参数(@p);一个包装函数递出一袋 $PSBoundParameters。
旁白:用展开传参提高可读性,转发调用方传入的内容。
模块 8 · OpsKit v0.1:Get-OpsServer、Get-OpsConfig 与 Test-OpsEndpoint
- 编写
Get-OpsServer(带ValidateSet的-Env,支持通配符的-Role/-Name),返回类型正确(Port为[int],Role为[string[]])的OpsKit.Server对象。 - 编写
Get-OpsConfig:两个参数集、Import-PowerShellDataFile(只读数据,不执行代码),并通过$PSBoundParameters判断后回退到DefaultEnv。 - 编写
Test-OpsEndpoint:按值和按属性名(IP/ComputerName/HostName+Port)接收管道输入,begin/process/end,带超时的TcpClient连接,每个目标一个结果对象。 - 用点源加载脚本载入 OpsKit,运行
Get-OpsServer -Env prod | Test-OpsEndpoint,并解读 Open / Timeout / ConnectionRefused / HostNotFound。
是什么:OpsKit v0.1
| 文件 | 函数 | 用到的本课技术 |
|---|---|---|
Private/Get-OpsDataPath.ps1 | 解析 ~/pslab/data/…(可用 $env:OPSKIT_DATA 覆盖) | 高级函数、[OutputType([string])] |
Public/Get-OpsServer.ps1 | 来自 inventory.json 的服务器 | ValidateSet、Position、[SupportsWildcards()]、ValidateScript + ErrorMessage、Write-Verbose、PSTypeName、帮助 |
Public/Get-OpsConfig.ps1 | 某个环境的设置,或 -All | 参数集、DefaultParameterSetName、[Alias('Environment')]、$PSCmdlet.ParameterSetName、$PSBoundParameters.ContainsKey、两个 [OutputType] |
Public/Test-OpsEndpoint.ps1 | TCP 端口检查 | ValueFromPipeline + ByPropertyName、[Alias('IP','ComputerName','HostName')]、ValidateRange、ValidateNotNullOrEmpty、begin/process/end |
为什么:用 TCP 检查而不是 ping
ICMP 经常被屏蔽,而且能 ping 通的主机上服务也可能已经死了。直接向服务端口建立 TCP 连接,回答的才是真正的问题。[System.Net.Sockets.TcpClient]::new().ConnectAsync($host, $port).Wait($ms) 提供有上限的等待:Test-NetConnection(仅 Windows)和 Test-Connection -TcpPort 也是可选方案,但 .NET 调用在所有平台上行为一致,还能精确控制超时。失败会以包装在 AggregateException 中的 SocketException 出现;GetBaseException() 把它解包,SocketErrorCode 给出稳定的名称(ConnectionRefused、HostNotFound……)。
怎么做:结果的含义(已在 Windows 11、7.6.10 上验证)
| 情形 | 结果 | 原因 |
|---|---|---|
127.0.0.1:18080 上的本地 TcpListener | Open,约 0–15 ms | 即使没有调用 AcceptTcpClient(),操作系统也会从监听队列完成握手 |
| 127.0.0.1:18081(没有监听),超时 500 ms | Timeout | 在 Windows 上,被拒绝的回环连接约 1 秒后才报告(实测 1033 ms);用 -TimeoutMs 5000 会得到 ConnectionRefused。在 Linux 上拒绝通常是立即的 |
localhost:18080,监听器只在 IPv4 上 | 500 ms 时 Timeout;超时更长时约 1 秒后 Open | localhost 先解析到 ::1,再到 127.0.0.1;IPv6 的尝试先被拒绝 |
| 10.30.x.x 清单地址 | Timeout | 虚构的私有地址:没有任何应答,所以耗尽整个超时(-TimeoutMs 300 时每台约 300 ms) |
nosuchhost.invalid | HostNotFound | DNS 失败;.invalid 是保留域,永远无法解析 |
何时:v0.1 的局限(后续课程修复)
- 函数被点源进会话,所以“私有”辅助函数是可见的,每个函数也都能看到你的变量(第 4 课:模块作用域)。
- 测试是逐个进行的:6 台不可达服务器 × 300 ms ≈ 2 秒;600 台服务器就要好几分钟(第 6 课:并行的
Invoke-OpsHealthCheck)。 - 没有重试、没有结构化日志、没有
-WhatIf——目前还不修改任何状态(第 5 课)。
localhost = 127.0.0.1”——当先尝试 IPv6 时就不是。③ “TCP 连通就证明服务正常”——它只证明有东西在接受连接;第 7 课会加入 HTTP 健康检查。④ “Import-PowerShellDataFile 和点源一个 .psd1 一样”——它只解析数据并拒绝代码,所以对配置是安全的。⑤ “用 ./OpsKit.ps1 运行加载脚本就能加载 OpsKit”——只有点源可以(模块 2)。图解:OpsKit v0.1 的数据流
图解:一次带超时的连接尝试
端点测试演示
选择一个目标,逐步经过绑定、校验、连接尝试和结果对象。所有结果都是 Windows 11 上 7.6.10 的真实运行。动画下方是 OpsKit 函数的交互式排错决策树。
交互式排错决策树:我的函数行为不对
命令参考
| 命令 | 用途 | 说明 |
|---|---|---|
. ~/pslab/OpsKit/OpsKit.ps1 | 加载 OpsKit v0.1 | 点、空格、路径 |
Get-OpsServer [-Env] <string[]> [-Role] [-Name] [-Path] | 清单对象 | OpsKit.Server |
Get-OpsConfig [[-Env] <string>] / Get-OpsConfig -All | 配置 | 两个参数集 |
Test-OpsEndpoint [-Target] <string> [[-Port] <int>] [-TimeoutMs] | TCP 检查 | 按值或按属性名接收管道输入 |
[System.Net.Sockets.TcpListener]::new([ipaddress]::Loopback, 18080) | 本地测试端点 | .Start() / .Stop() |
Import-PowerShellDataFile | 安全读取 .psd1 | 不执行代码 |
. ~/pslab/OpsKit/OpsKit.ps1 Get-Command -Name *-Ops* | Format-Table CommandType, Name, Source -AutoSize (Get-OpsServer).Count Get-OpsServer -Env prod -Role web | Format-Table Name, Env, Role, IP Get-OpsServer prod, staging -Role db | Format-Table Name, Env, IP Get-OpsServer -Name 'web-*' -Env dev, prod | Format-Table Name, Env
CommandType Name Source
----------- ---- ------
Function Get-OpsConfig
Function Get-OpsDataPath
Function Get-OpsServer
Function Test-OpsEndpoint
12
Name Env Role IP
---- --- ---- --
web-01 prod {web} 10.30.1.41
web-02 prod {web} 10.30.1.42
edge-01 prod {web, api} 10.30.2.51
Name Env IP
---- --- --
db-01 staging 10.20.1.33
db-01 prod 10.30.1.44
Name Env
---- ---
web-01 dev
web-01 prod
web-02 prod
注意 Source 为空:这些是独立函数,不是模块命令。第 4 课之后这一列会显示 OpsKit。另外 edge-01(角色 "web,api")能匹配 -Role web,因为函数把角色字符串拆成了数组。
Get-OpsConfig -Env prod Get-OpsConfig -Verbose | Format-List Env, Region, HealthUrl (Get-OpsConfig -All).Health Get-OpsConfig -Env prod -All Get-Command Get-OpsConfig -Syntax
Env : prod
Region : canadacentral
HealthUrl : https://shop.example.com/healthz
RequireConfirm : True
TimeoutSec : 5
Retries : 3
VERBOSE: No -Env given; using DefaultEnv 'dev'
Env : dev
Region : canadacentral
HealthUrl : http://10.10.1.21:8080/healthz
Name Value
---- -----
TimeoutSec 5
BackoffSec {1, 2, 4}
Retries 3
Get-OpsConfig: Parameter set cannot be resolved using the specified named parameters. One or more parameters issued cannot be used together or an insufficient number of parameters were provided.
Get-OpsConfig [[-Env] <string>] [-Path <string>] [<CommonParameters>]
Get-OpsConfig -All [-Path <string>] [<CommonParameters>]
$listener = [System.Net.Sockets.TcpListener]::new([ipaddress]::Loopback, 18080)
$listener.Start()
Test-OpsEndpoint -Target 127.0.0.1 -Port 18080
'127.0.0.1', 'localhost' | Test-OpsEndpoint -Port 18080 | Format-Table Target, Port, Open, Result
Test-OpsEndpoint localhost 18080 -TimeoutMs 5000 | Format-Table Target, Port, Open, Result, Ms -AutoSize
Test-OpsEndpoint 127.0.0.1 18081 -TimeoutMs 5000 | Format-Table Target, Port, Open, Result, Ms -AutoSize
[System.Net.Dns]::GetHostAddresses('localhost').IPAddressToString
$listener.Stop()
Name : Target : 127.0.0.1 Port : 18080 Open : True Result : Open Ms : 13 Target Port Open Result ------ ---- ---- ------ 127.0.0.1 18080 True Open localhost 18080 False Timeout Target Port Open Result Ms ------ ---- ---- ------ -- localhost 18080 True Open 1004 Target Port Open Result Ms ------ ---- ---- ------ -- 127.0.0.1 18081 False ConnectionRefused 1033 ::1 127.0.0.1
如何验证:1 秒左右的数字来自 Windows TCP 栈对被拒绝连接的重试;这解释了为什么 localhost 在 500 ms 时超时,而 127.0.0.1 瞬间完成。常见错误:用 localhost 测试一个只监听 IPv4 的服务,然后断定服务挂了。生产用法:测试客户端实际使用的地址;记录 Result 而不只是 Open,这样就能区分拒绝(服务停了)和超时(防火墙/路由)。
$listener = [System.Net.Sockets.TcpListener]::new([ipaddress]::Loopback, 18080)
$listener.Start()
Get-OpsServer -Env prod | Test-OpsEndpoint -TimeoutMs 300 -Verbose | Format-Table Name, Target, Port, Open, Result, Ms -AutoSize
@(
[pscustomobject]@{ Name = 'local-ok'; ComputerName = '127.0.0.1'; Port = 18080 }
[pscustomobject]@{ Name = 'local-off'; ComputerName = '127.0.0.1'; Port = 18081 }
[pscustomobject]@{ Name = 'bad-dns'; HostName = 'nosuchhost.invalid'; Port = 443 }
) | Test-OpsEndpoint | Format-Table Name, Target, Port, Open, Result -AutoSize
Test-OpsEndpoint -Target 127.0.0.1 -Port 70000
VERBOSE: 0 of 6 endpoint(s) open Name Target Port Open Result Ms ---- ------ ---- ---- ------ -- web-01 10.30.1.41 8080 False Timeout 312 web-02 10.30.1.42 8080 False Timeout 310 api-01 10.30.1.43 8080 False Timeout 310 edge-01 10.30.2.51 8080 False Timeout 309 db-01 10.30.1.44 8080 False Timeout 310 bastion-01 10.30.2.10 8080 False Timeout 310 Name Target Port Open Result ---- ------ ---- ---- ------ local-ok 127.0.0.1 18080 True Open local-off 127.0.0.1 18081 False Timeout bad-dns nosuchhost.invalid 443 False HostNotFound Test-OpsEndpoint: Cannot validate argument on parameter 'Port'. The 70000 argument is greater than the maximum allowed range of 65535. Supply an argument that is less than or equal to 65535 and then try the command again.
10.x 的超时是预期的:清单地址在你的网络中并不存在。VERBOSE 行来自 end 块,在最后一个对象之后产生;它出现在表格上方,是因为 Format-Table -AutoSize 要等管道结束才输出所有行,而 verbose 信息是立即写出的。不带 -AutoSize 时,Format-Table 根据前几行确定列宽(我们的一次运行中把 edge-01 截断成了 edge-…),VERBOSE 行则出现在各行之后。
目标:编写 OpsKit v0.1 并端到端运行。环境:pwsh 7.6、VS Code、模块 0 中的 ~/pslab/OpsKit。费用:无;监听器只绑定回环地址。
~/pslab/OpsKit/Private/Get-OpsDataPath.ps1:
function Get-OpsDataPath {
# Private helper: where the course data lives. $env:OPSKIT_DATA overrides the
# default (Lesson 8's tests use that). Until Lesson 4, "Private" is only a folder
# name: dot-sourcing makes this function visible in your session like any other.
[CmdletBinding()]
[OutputType([string])]
param(
[string]$ChildPath
)
$root = if ($env:OPSKIT_DATA) { $env:OPSKIT_DATA } else { Join-Path $HOME 'pslab' 'data' }
if ($ChildPath) { Join-Path $root $ChildPath } else { $root }
}Get-OpsServer——~/pslab/OpsKit/Public/Get-OpsServer.ps1:
function Get-OpsServer {
<#
.SYNOPSIS
Lists servers from the OpsKit inventory.
.DESCRIPTION
Reads inventory.json and returns one OpsKit.Server object per server.
Filter with -Env, -Role and -Name; -Role and -Name accept wildcards.
.PARAMETER Env
One or more environments: dev, staging, prod. All environments if omitted.
.PARAMETER Role
A role such as web, api, db or bastion. 'web' also matches the multi-role server edge-01.
.PARAMETER Name
Server name filter, for example 'web-*'.
.PARAMETER Path
The inventory file. Default: ~/pslab/data/inventory.json.
.EXAMPLE
Get-OpsServer -Env prod -Role web
.EXAMPLE
Get-OpsServer -Env prod | Test-OpsEndpoint
.OUTPUTS
OpsKit.Server
#>
[CmdletBinding()]
[OutputType('OpsKit.Server')]
param(
[Parameter(Position = 0)]
[ValidateSet('dev', 'staging', 'prod')]
[string[]]$Env,
[SupportsWildcards()]
[string]$Role = '*',
[SupportsWildcards()]
[string]$Name = '*',
[ValidateScript({ Test-Path -LiteralPath $_ -PathType Leaf },
ErrorMessage = 'Inventory file not found: {0}')]
[string]$Path = (Get-OpsDataPath -ChildPath 'inventory.json')
)
Write-Verbose "Reading $Path"
$inventory = Get-Content -LiteralPath $Path -Raw | ConvertFrom-Json
foreach ($s in $inventory) {
if ($Env -and $s.Env -notin $Env) { continue }
if ($s.Name -notlike $Name) { continue }
$roles = $s.Role -split ','
if (-not ($roles -like $Role)) { continue }
[pscustomobject]@{
PSTypeName = 'OpsKit.Server'
Name = $s.Name
Env = $s.Env
Role = $roles
IP = $s.IP
Port = [int]$s.Port
Region = $s.Region
Monitored = [bool]$s.Monitored
}
}
}
对数组使用 $roles -like $Role 会返回匹配的元素(第 2 课:数组上的运算符),所以 -not (…) 表示“没有任何角色匹配”。参数名叫 $Env;它与 $env: 驱动器无关(模块 2 测验)。
Get-OpsConfig——~/pslab/OpsKit/Public/Get-OpsConfig.ps1:
function Get-OpsConfig {
<#
.SYNOPSIS
Reads the OpsKit configuration file (opskit.config.psd1).
.DESCRIPTION
Uses Import-PowerShellDataFile, which parses the file as data and never runs code.
Returns the settings of one environment (DefaultEnv from the file when -Env is
omitted); -All returns the whole configuration as a hashtable.
.PARAMETER Env
dev, staging or prod. Alias: Environment.
.PARAMETER All
Return the complete configuration hashtable.
.EXAMPLE
Get-OpsConfig -Env prod
.EXAMPLE
(Get-OpsConfig -All).Health.TimeoutSec
#>
[CmdletBinding(DefaultParameterSetName = 'Env')]
[OutputType('OpsKit.EnvConfig', ParameterSetName = 'Env')]
[OutputType([hashtable], ParameterSetName = 'All')]
param(
[Parameter(ParameterSetName = 'Env', Position = 0)]
[Alias('Environment')]
[ValidateSet('dev', 'staging', 'prod')]
[string]$Env,
[Parameter(ParameterSetName = 'All', Mandatory)]
[switch]$All,
[string]$Path = (Get-OpsDataPath -ChildPath 'opskit.config.psd1')
)
$config = Import-PowerShellDataFile -LiteralPath $Path
if ($PSCmdlet.ParameterSetName -eq 'All') {
return $config
}
if (-not $PSBoundParameters.ContainsKey('Env')) {
$Env = $config.DefaultEnv
Write-Verbose "No -Env given; using DefaultEnv '$Env'"
}
$e = $config.Environments[$Env]
[pscustomobject]@{
PSTypeName = 'OpsKit.EnvConfig'
Env = $Env
Region = $e.Region
HealthUrl = $e.HealthUrl
RequireConfirm = [bool]$e.RequireConfirm
TimeoutSec = $config.Health.TimeoutSec
Retries = $config.Health.Retries
}
}Test-OpsEndpoint——~/pslab/OpsKit/Public/Test-OpsEndpoint.ps1:
function Test-OpsEndpoint {
<#
.SYNOPSIS
Tests whether a TCP port answers, with a short timeout.
.DESCRIPTION
Accepts host names or IP addresses as arguments or from the pipeline.
Objects with an IP, ComputerName or HostName property (Get-OpsServer,
Import-Csv servers.csv) bind by property name; a Port property binds too.
.PARAMETER Target
Host name or IP address. Aliases: IP, ComputerName, HostName.
.PARAMETER Port
TCP port, 1-65535. Default 8080 (the inventory's port).
.PARAMETER TimeoutMs
How long to wait for each connection, in milliseconds. Default 500.
.EXAMPLE
Test-OpsEndpoint -Target 127.0.0.1 -Port 18080
.EXAMPLE
Get-OpsServer -Env prod | Test-OpsEndpoint -TimeoutMs 300
.OUTPUTS
OpsKit.EndpointResult
#>
[CmdletBinding()]
[OutputType('OpsKit.EndpointResult')]
param(
[Parameter(Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[Alias('IP', 'ComputerName', 'HostName')]
[ValidateNotNullOrEmpty()]
[string]$Target,
[Parameter(Position = 1, ValueFromPipelineByPropertyName)]
[ValidateRange(1, 65535)]
[int]$Port = 8080,
[Parameter(ValueFromPipelineByPropertyName)]
[string]$Name,
[ValidateRange(50, 30000)]
[int]$TimeoutMs = 500
)
begin {
$tested = 0
$open = 0
}
process {
$tested++
$client = [System.Net.Sockets.TcpClient]::new()
$timer = [System.Diagnostics.Stopwatch]::StartNew()
$result = 'Open'
try {
if (-not $client.ConnectAsync($Target, $Port).Wait($TimeoutMs)) {
$result = 'Timeout'
}
}
catch {
# Wait() wraps socket errors in an AggregateException
$inner = $_.Exception.GetBaseException()
$result = if ($inner -is [System.Net.Sockets.SocketException]) { [string]$inner.SocketErrorCode } else { $inner.Message }
}
finally {
$timer.Stop()
$client.Dispose()
}
if ($result -eq 'Open') { $open++ }
[pscustomobject]@{
PSTypeName = 'OpsKit.EndpointResult'
Name = $Name
Target = $Target
Port = $Port
Open = $result -eq 'Open'
Result = $result
Ms = [int]$timer.ElapsedMilliseconds
}
}
end {
Write-Verbose "$open of $tested endpoint(s) open"
}
}. ~/pslab/OpsKit/OpsKit.ps1,然后运行“命令”分页的前两个代码块。检查 Get-Help Get-OpsServer -Examples 和 Get-OpsServer -Env dev | Get-Member(TypeName 为 OpsKit.Server,Port 是 int,Role 是 string[])。$listener.Stop() Test-OpsEndpoint 127.0.0.1 18080 | Select-Object Target, Port, Result
Target Port Result ------ ---- ------ 127.0.0.1 18080 Timeout
IP;没有 Port 列 → 默认 8080):
Import-Csv ~/pslab/data/servers.csv | Where-Object Env -eq 'dev' | Test-OpsEndpoint -TimeoutMs 200 | Format-Table Name, Target, Port, Result
Name Target Port Result ---- ------ ---- ------ web-01 10.10.1.21 8080 Timeout api-01 10.10.1.22 8080 Timeout db-01 10.10.1.23 8080 Timeout
$listener.Stop() 已经执行(或关闭终端)。OpsKit 文件保留——综合实验和第 4 课都要用。案例 1:网络变更后“所有端点都挂了”
问题:一次早间检查报告所有 prod 端点都不可用。根因:检查只记录了 Open = False;实际上所有结果都是 Timeout,因为监控主机被挪到了一个没有到服务器路由的 VLAN——服务本身没问题。修复:保留 Result 代码(Timeout、ConnectionRefused、HostNotFound)并按它分组:… | Group-Object Result。大量同时超时通常指向网络路径,拒绝则指向服务。
案例 2:耗时 20 分钟的健康检查
问题:一个脚本对 400 台主机使用 Test-NetConnection;每台不可达主机大约要 20 秒。修复:使用像 Test-OpsEndpoint -TimeoutMs 500 这样有上限的连接,再加上并行(第 6 课)。务必做预算:主机数 × 超时 ÷ 并行度。
案例 3:会执行代码的配置
问题:一个工具用 . ./settings.ps1 加载设置;一次好心的编辑加了一行 Remove-Item,每次启动都会执行。修复:把设置存进 .psd1,用 Import-PowerShellDataFile 读取,它只接受字面量数据(字符串、数字、数组、哈希表、$true/$false/$null)。
常见错误与修复
The term 'Get-OpsServer' is not recognized …
原因:当前会话没有加载 OpsKit,或者用 &/./ 而不是点源加载。
. ~/pslab/OpsKit/OpsKit.ps1 Get-Command -Name *-Ops*
Cannot validate argument on parameter 'Path'. Inventory file not found: …
原因:~/pslab/data 不存在,或者 $env:OPSKIT_DATA 指向了别处。
修复:运行 ~/pslab/New-LabData.ps1;Get-OpsDataPath 显示正在使用的文件夹。
每个结果都是 Timeout,连 127.0.0.1 也是
原因:监听器没有启动或已经停止、端口不对,或者在 Windows 上拒绝比 -TimeoutMs 来得慢。
修复:检查 $listener.Server.IsBound;用 -TimeoutMs 5000 重试,观察是否为 ConnectionRefused。
Exception calling "Start" with "0" argument(s): "Only one usage of each socket address (protocol/network address/port) is normally permitted."
原因:18080 端口已被占用(可能是前面步骤留下的监听器)。
修复:$listener.Stop(),或换一个端口:Get-NetTCPConnection -LocalPort 18080(Windows)可以显示占用者。
1. 显示端点未开放的 prod 服务器及原因,按名称排序。
Get-OpsServer -Env prod | Test-OpsEndpoint -TimeoutMs 300 |
Where-Object { -not $_.Open } | Sort-Object Name | Select-Object Name, Target, Result2. 测试时使用某个环境配置的健康检查超时。
$cfg = Get-OpsConfig -Env staging Get-OpsServer -Env staging | Test-OpsEndpoint -TimeoutMs ($cfg.TimeoutSec * 1000)
每台不可达服务器 5 秒——3 台还可以,很多台就太慢了(第 6 课)。
为什么 Test-OpsEndpoint 为每个目标输出一个结果对象,而不是写“OK”/“FAILED”文本?
对象保留了细节(目标、端口、结果代码、延迟),可以筛选、分组、导出为 JSON/CSV,也可以在测试中断言。文本会迫使下一个使用者再次解析——这正是 PowerShell 设计出来要消除的问题(第 1 课)。
已验证的教学视频
没有找到讲解带超时 TcpClient 的 TCP 检查的已验证视频;请使用本模块和 .NET 文档。
官方文档
视频分镜(约 90 秒)
画面:三个文件落入 Public/,加载脚本把它们点源进会话。
旁白:OpsKit v0.1 就是三个函数加一个加载脚本。
画面:服务器对象流入 Test-OpsEndpoint;IP 和 Port 徽章咔嗒一声扣进参数。
旁白:按属性名的管道绑定让工具可以组合。
画面:一块结果看板:一个绿色 Open(本地监听器),六个琥珀色 Timeout。
旁白:记录原因,而不只是通过或失败。
命令速查表
1. 函数与输出
function Get-X { param([string]$Name = 'x') "out $Name" }
Get-X -Name a; Get-X a # NOT Get-X(a, b)
$null = $list.Add($i) # discard (fastest)
[void]$sb.Append('x'); cmd | Out-Null
return # exit only; earlier output stays
, $array # emit the array as ONE object
Write-Output $list -NoEnumerate
@(Get-X).Count # caller-side: always an array2. 作用域
$x # read: walks up the CALL chain
$x = 1 # write: current scope only
$script:x++; $global:x = 1; $private:x = 's'
Get-Variable x -Scope 1 # parent scope
. ./lib.ps1 # dot-source: stays in your scope
. ~/pslab/OpsKit/OpsKit.ps1 # load OpsKit v0.1
1..3 | ForEach-Object -Parallel { $using:x }
{ $x }.GetNewClosure()3. 高级函数
function Get-Y {
[CmdletBinding()]
param([string]$Name)
Write-Verbose "name=$Name" # -Verbose
if ($PSBoundParameters.ContainsKey('Name')) { … }
$PSCmdlet.ParameterSetName
}
(Get-Command Get-Y).CmdletBinding # True
Get-Y -Nmae x # error: parameter cannot be found4. 参数与参数集
[CmdletBinding(DefaultParameterSetName = 'ByEnv')]
param(
[Parameter(Mandatory, Position = 0, ParameterSetName = 'ByName')]
[string]$Name,
[Parameter(ParameterSetName = 'ByEnv')] [string]$Env = 'dev',
[Alias('Address')] [ipaddress]$IP,
[switch]$Force, # -Force:$false
[Parameter(Mandatory)] [AllowEmptyString()] [string]$Note
)
Get-Command Get-Node -Syntax5. 校验与补全
[ValidateSet('dev', 'staging', 'prod')]
[ValidatePattern('^[a-z]+-\d{2}$', ErrorMessage = 'bad name {0}')]
[ValidateRange(1, 65535)] [ValidateRange('Positive')]
[ValidateScript({ Test-Path $_ }, ErrorMessage = 'not found: {0}')]
[ValidateNotNullOrEmpty()] [ValidateNotNullOrWhiteSpace()]
[ArgumentCompletions('a', 'b')]
[ArgumentCompleter({ param($c, $p, $w, $a, $f) … })]
Register-ArgumentCompleter -CommandName C -ParameterName P -ScriptBlock { … }
(TabExpansion2 'C -P ' 5).CompletionMatches.CompletionText6. 管道输入
param(
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[Alias('IP', 'ComputerName')]
[string[]]$Target
)
begin { $n = 0 } # params from pipeline NOT bound yet
process { foreach ($t in $Target) { $n++; $t } } # per object
end { Write-Verbose "$n done" }
Trace-Command -Name ParameterBinding -PSHost -Expression { … }7. 输出类型、帮助、展开传参
[OutputType('OpsKit.Server')] # metadata only
[pscustomobject]@{ PSTypeName = 'OpsKit.Server'; Name = 'web-01' }
$o.PSObject.TypeNames -contains 'OpsKit.Server'
Update-TypeData -TypeName OpsKit.Server -DefaultDisplayPropertySet Name, Env, IP
param([PSTypeName('OpsKit.Server')] $Server)
<# .SYNOPSIS … #> # top of body, or ≤ 1 blank line above function
$p = @{ Env = 'prod'; Role = 'web' }; Get-OpsServer @p -Role api
Inner @PSBoundParameters; $null = $PSBoundParameters.Remove('X')
Get-Verb -Verb Fetch # nothing → unapproved8. OpsKit v0.1
. ~/pslab/OpsKit/OpsKit.ps1 Get-OpsServer -Env prod -Role web Get-OpsConfig -Env prod; (Get-OpsConfig -All).Health $l = [System.Net.Sockets.TcpListener]::new([ipaddress]::Loopback, 18080); $l.Start() Test-OpsEndpoint 127.0.0.1 18080 Get-OpsServer -Env prod | Test-OpsEndpoint -TimeoutMs 300 | Group-Object Result $l.Stop() ~/pslab/OpsKit/tests/Invoke-OpsKitCheck.ps1; $LASTEXITCODE
综合实验 + 结业测验
Get-OpsServer -Env prod | Test-OpsEndpoint 加上一个本地端点——并用 ~/pslab/OpsKit/tests/Invoke-OpsKitCheck.ps1 证明它:一个包含 13 项检查和退出码的验收脚本场景
团队想要一份快速的“prod 端点可达吗?”报告,同时希望在接下来几课重构 OpsKit 函数时,能保证它们的契约不变。你将:(1) 运行一份端到端报告,把 prod 清单和一个本地模拟端点混在一起,并保存为 JSON;(2) 编写一个验收脚本:加载 OpsKit,检查清单数量、类型、配置、校验、对未知参数的拒绝以及管道绑定,然后以 0(全部通过)或 1(任何失败)退出——与第 1 课 Test-LabData.ps1 的契约相同,只是现在由高级函数构成。
. ~/pslab/OpsKit/OpsKit.ps1
$listener = [System.Net.Sockets.TcpListener]::new([ipaddress]::Loopback, 18080)
$listener.Start()
$targets = @(Get-OpsServer -Env prod) + [pscustomobject]@{ Name = 'local-mock'; IP = '127.0.0.1'; Port = 18080 }
$report = $targets | Test-OpsEndpoint -TimeoutMs 300
$listener.Stop()
$report | Format-Table Name, Target, Port, Open, Result, Ms -AutoSize
$report | Group-Object Result -NoElement | Format-Table Count, Name -AutoSize
$report | ConvertTo-Json -Depth 2 | Set-Content ~/pslab/tmp/endpoints.json
(Get-Content ~/pslab/tmp/endpoints.json -Raw | ConvertFrom-Json).Count
Name Target Port Open Result Ms
---- ------ ---- ---- ------ --
web-01 10.30.1.41 8080 False Timeout 300
web-02 10.30.1.42 8080 False Timeout 325
api-01 10.30.1.43 8080 False Timeout 324
edge-01 10.30.2.51 8080 False Timeout 309
db-01 10.30.1.44 8080 False Timeout 311
bastion-01 10.30.2.10 8080 False Timeout 311
local-mock 127.0.0.1 18080 True Open 0
Count Name
----- ----
1 Open
6 Timeout
7
@(…) + [pscustomobject]… 在一个管道中混合了两种形状的对象;两者都能绑定,因为 -Target 有别名 IP,而 Port/Name 按属性名绑定。测试一结束就停止监听器——报告已经在 $report 中了。
~/pslab/OpsKit/tests/Invoke-OpsKitCheck.ps1:
<#
.SYNOPSIS
Acceptance checks for OpsKit v0.1 (Lesson 3). Lesson 8 replaces them with Pester tests.
.DESCRIPTION
Loads OpsKit by dot-sourcing OpsKit.ps1, then checks the inventory, the configuration,
parameter validation, pipeline binding and a real TCP test against a local listener.
Exit codes: 0 all checks passed; 1 at least one check failed.
.EXAMPLE
~/pslab/OpsKit/tests/Invoke-OpsKitCheck.ps1 | Format-Table
#>
#Requires -Version 7.4
[CmdletBinding()]
param(
[ValidateRange(1024, 65535)]
[int]$LocalPort = 18080
)
. (Join-Path $PSScriptRoot '..' 'OpsKit.ps1')
function New-Check {
[CmdletBinding()]
param(
[Parameter(Mandatory, Position = 0)] [string]$Name,
[Parameter(Mandatory, Position = 1)] [AllowEmptyString()] [string]$Expected,
[Parameter(Mandatory, Position = 2)] [AllowEmptyString()] [AllowNull()] [string]$Actual
)
[pscustomobject]@{
PSTypeName = 'OpsKit.Check'
Check = $Name
Expected = $Expected
Actual = $Actual
Passed = $Expected -eq $Actual
}
}
function Get-ErrorId {
# Runs a script block and returns the FullyQualifiedErrorId of the first error, or 'no error'.
param([scriptblock]$ScriptBlock)
$ErrorActionPreference = 'Stop' # local copy, inherited by the script block (Module 2)
try { $null = & $ScriptBlock; 'no error' }
catch { ($_.FullyQualifiedErrorId -split ',')[0] }
}
$listener = [System.Net.Sockets.TcpListener]::new([ipaddress]::Loopback, $LocalPort)
$listener.Start()
try {
$results = @(
New-Check 'all servers' 12 @(Get-OpsServer).Count
New-Check 'prod servers' 6 @(Get-OpsServer -Env prod).Count
New-Check 'prod web servers' 'web-01,web-02,edge-01' ((Get-OpsServer -Env prod -Role web).Name -join ',')
New-Check 'type name' 'OpsKit.Server' @(Get-OpsServer -Env dev)[0].PSObject.TypeNames[0]
New-Check 'Port is a number' 'Int32' @(Get-OpsServer -Env dev)[0].Port.GetType().Name
New-Check 'prod requires confirm' 'True' (Get-OpsConfig -Env prod).RequireConfirm
New-Check 'default environment' 'dev' (Get-OpsConfig).Env
New-Check 'unknown env rejected' 'ParameterArgumentValidationError' (Get-ErrorId { Get-OpsServer -Env production })
New-Check 'unknown param rejected' 'NamedParameterNotFound' (Get-ErrorId { Get-OpsServer -Environment prod })
New-Check 'port range validated' 'ParameterArgumentValidationError' (Get-ErrorId { Test-OpsEndpoint 127.0.0.1 -Port 0 })
New-Check 'local listener open' 'True' (Test-OpsEndpoint 127.0.0.1 $LocalPort).Open
New-Check 'pipeline binds IP+Port' "127.0.0.1:${LocalPort}:True" $(
$r = [pscustomobject]@{ IP = '127.0.0.1'; Port = $LocalPort } | Test-OpsEndpoint
'{0}:{1}:{2}' -f $r.Target, $r.Port, $r.Open)
New-Check 'one result per server' 6 @(Get-OpsServer -Env prod | Test-OpsEndpoint -TimeoutMs 100).Count
)
}
finally {
$listener.Stop()
}
$results
$failed = @($results | Where-Object { -not $_.Passed })
if ($failed.Count -gt 0) {
Write-Warning "$($failed.Count) check(s) failed: $($failed.Check -join ', ')"
exit 1
}
exit 0
New-Check 现在是带必需位置参数的高级函数——第 1 课的 -join 错误会被拒绝。Get-ErrorId 在自己的作用域中设置 $ErrorActionPreference = 'Stop';它调用的脚本块通过动态作用域(模块 2)继承这个首选项,所以任何错误都能被捕获,函数返回 FullyQualifiedErrorId 的第一部分。(参数绑定和校验错误即使没有它也会被捕获,因为它们会终止语句。)
~/pslab/OpsKit/tests/Invoke-OpsKitCheck.ps1 | Format-Table -AutoSize; "exit=$LASTEXITCODE"
Check Expected Actual Passed ----- -------- ------ ------ all servers 12 12 True prod servers 6 6 True prod web servers web-01,web-02,edge-01 web-01,web-02,edge-01 True type name OpsKit.Server OpsKit.Server True Port is a number Int32 Int32 True prod requires confirm True True True default environment dev dev True unknown env rejected ParameterArgumentValidationError ParameterArgumentValidationError True unknown param rejected NamedParameterNotFound NamedParameterNotFound True port range validated ParameterArgumentValidationError ParameterArgumentValidationError True local listener open True True True pipeline binds IP+Port 127.0.0.1:18080:True 127.0.0.1:18080:True True one result per server 6 6 True exit=0
编写这项检查时发现的一个真实 bug:第一个版本用 (Get-OpsServer -Env dev | Select-Object -First 1).PSObject.TypeNames[0] 读取类型名,结果因为得到 Selected.System.Management.Automation.PSCustomObject 而失败(模块 7,案例 1)。脚本现在使用 @(Get-OpsServer -Env dev)[0]。
Test-OpsEndpoint.ps1 中删掉 [Alias('IP', …)] 这一行,重新运行,然后恢复。
$f = '~/pslab/OpsKit/Public/Test-OpsEndpoint.ps1'
$orig = Get-Content $f -Raw
(Get-Content $f) -notmatch "^\s+\[Alias\('IP'" | Set-Content $f
~/pslab/OpsKit/tests/Invoke-OpsKitCheck.ps1 2>$null | Where-Object { -not $_.Passed } | Format-Table -AutoSize; "exit=$LASTEXITCODE"
Set-Content $f -Value $orig -NoNewline # restore
WARNING: 1 check(s) failed: pipeline binds IP+Port
Check Expected Actual Passed
----- -------- ------ ------
pipeline binds IP+Port 127.0.0.1:18080:True @{IP=127.0.0.1; Port=18080}:18080:False False
exit=1
这正是模块 6 的类型转换陷阱:没有别名时,对象被转换成文本 @{IP=127.0.0.1; Port=18080} 并被当作主机名;Port 仍然按属性名绑定。
pwsh -NoProfile -NonInteractive -File ~/pslab/OpsKit/tests/Invoke-OpsKitCheck.ps1 | Out-Null; "exit=$LASTEXITCODE"
exit=0
开放式自测
1. 逐步说明 Get-OpsServer -Env prod | Test-OpsEndpoint -TimeoutMs 300 执行时发生了什么。
两个命令都被解析为函数。绑定命名实参:-Env prod 转换为 string[] 并通过 ValidateSet;-TimeoutMs 300 转换为 int 并通过 ValidateRange(50, 30000)。-Target 的必需检查被推迟,因为它接受管道输入。两个 begin 块运行(Test-OpsEndpoint 初始化计数器)。Get-OpsServer 的 end 块(即函数体)读取 JSON,逐个输出 OpsKit.Server 对象;对每个对象,绑定器先为 -Target 尝试 ByValue(跳过——不转换时它不是字符串),再尝试 ByPropertyName:IP → -Target(别名)、Port → -Port、Name → -Name;然后 process 执行有上限的连接并输出一个结果。最后一个对象之后,end 写出 verbose 汇总。
2. 为什么加载器不能写成 Import-OpsKit { foreach (…) { . $file } } 这样的函数?
在函数内部点源,会把函数定义在该函数的作用域中,函数返回时作用域就消失了。你必须点源这个函数本身(. Import-OpsKit),或者使用 function global:… 定义。第 4 课用模块正规地解决这个问题。
3. 说出让函数达到“cmdlet 水准”的三点。
严格绑定,参数带类型和校验([CmdletBinding()]、Validate*、参数集);正确的管道行为(process、带别名的 ByPropertyName、每进一个对象出一个对象);可发现性(批准的动词、带示例的基于注释的帮助、[OutputType] 和 PSTypeName)。另外:不用 Write-Host/Format-* 输出数据,诊断信息用 Write-Verbose。
4. 同事的函数返回 0 1 2 report。你首先看哪里?
看返回值没有被捕获的方法调用——典型的是 ArrayList.Add()——以及 New-Item 之类的 cmdlet。把结果管道到 ForEach-Object { $_.GetType().Name },看看泄漏了什么(模块 1)。
来源与版本说明
| 主题 | 验证结果 | 来源(访问日期 2026-11-24) |
|---|---|---|
| 函数输出 | 未捕获的值都是输出;return 只负责退出;@()、单元素数组和 List[T] 的展开;逗号与 -NoEnumerate;$null = / [void] / Out-Null 的耗时(实验机上 100,000 次调用分别为 605 / 653 / 1,202 ms) | about_Functions;about_Return;本课的实际运行 |
| 作用域 | 读穿透/赋值即副本;提示符下 $script: = global;$private:;点源脚本和函数;-Parallel 中的 $using:;GetNewClosure() | about_Scopes;about_Remote_Variables;about_Script_Blocks |
| 高级函数 | 任何 [Parameter()] 或 [CmdletBinding()] 都使函数成为高级函数;7.6 中有 12 个通用参数(含 ProgressAction);拒绝未知/多余实参;-Debug 不再提示 | about_Functions_Advanced;about_Functions_CmdletBindingAttribute;about_CommonParameters;about_Functions_Advanced_Methods |
| 参数 | 类型转换(8080.6 → 8081,[bool] 拒绝字符串)、-NonInteractive 下的 Mandatory、位置绑定规则、开关、参数集及其错误信息 | about_Functions_Advanced_Parameters;about_Parameter_Sets |
| 校验与补全 | 所有 Validate* 信息均已复现;默认值不校验;赋值时再次校验;补全器用 TabExpansion2 测试 | about_Functions_Argument_Completion;Register-ArgumentCompleter |
| 管道输入 | 缺少 process → 只处理最后一个对象;[string] 上带转换的 ByValue;别名绑定;对函数运行 Trace-Command 的输出 | about_Pipelines;Trace-Command |
| 输出、帮助、展开传参 | [OutputType] 不强制;PSTypeName;Select-Object -First 对 PSCustomObject 前置 Selected.*;帮助位置(6 种情形);显式参数覆盖展开的值;100 个批准的动词 | about_Comment_Based_Help;about_Functions_OutputTypeAttribute;about_Splatting;Update-TypeData;批准的动词 |
| OpsKit v0.1 / TCP | 本地 TcpListener 为 Open;Windows 上被拒绝的回环连接约 1 秒后报告;localhost → 先 ::1 后 127.0.0.1;10.x 为 Timeout;.invalid 为 HostNotFound | TcpClient.ConnectAsync;Import-PowerShellDataFile;本课的实际运行 |
视频验证说明
只列出 2026-11-24 通过 YouTube oEmbed(https://www.youtube.com/oembed?url=…&format=json)核对过标题和频道的视频:
- 8 Functions and Advance functions in PowerShell — Ashish Raj(模块 1、4)
- PowerShell Function Scope Explained: Local, Script & Global Variables Tutorial — CodeLucky(模块 2)
- MICROSOFT Windows PowerShell – How variable scope works in functions — HardReset_Pro(模块 2)
- Introduction to PowerShell: Module 4 - Dot-Sourcing — Bryan Cafferky(模块 2)
- PowerShell CmdletBinding Tutorial - Advanced Functions Explained for Beginners — CodeLucky(模块 3、8)
- A Brief explanation of CmdletBinding — Info Tech Zone(模块 3)
- MICROSOFT Windows PowerShell – How to Use CmdletBinding in Functions — HardReset_Pro(模块 3)
- PowerShell Advanced Functions — Adam Driscoll(模块 4–8)
- PowerShell Parameter Validation: ValidateSet, ValidateRange, ValidatePattern & More — CodeLucky(模块 5)
- Powershell Basics - Pipeline Parameter Binding in DETAIL — Chasse TAC(模块 6)
- 来自第 1 课已验证列表:Learn PowerShell in Less Than 2 Hours — K12 Engineer;PowerShell Master Class - PowerShell Fundamentals — John Savill's Technical Training
oEmbed 只能验证标题和频道;这些视频并没有逐段观看,描述来自标题和搜索摘要。它们大多使用 Windows PowerShell 5.1 或早期的 PowerShell 7;行为不同之处(例如 -Debug 提示、校验特性上的 ErrorMessage)以本课为准。没有找到讲解函数输出语义、基于注释的帮助放置位置、PSTypeName 或带超时 TCP 检查的已验证视频。
语音讲解说明
“语音”分页使用浏览器内置的 Web Speech API(zh-CN)朗读讲解稿,不需要网络访问。讲解稿和分镜可以交给 TTS 或视频工具;本教材不嵌入音频或视频文件。
已知限制
- 运行环境:所有标注“实际输出(7.6.10)”的代码块都在 Windows 11 + PowerShell 7.6.10 上生成;主目录路径已替换为
C:\Users\labadmin\…。命令在同一会话中逐条运行,如同在提示符下输入;错误以默认的 ConciseView 显示。未在 Linux 或 macOS 上运行:TCP 耗时(回环拒绝约 1 秒、localhost先尝试::1)是 Windows 上的观察结果;在 Linux 上拒绝通常会立即报告——本课未验证。 - 无法在非交互运行中捕获的交互行为——Mandatory 提示与
!?帮助、按 Tab 键——根据文档描述;补全改用TabExpansion2验证。 - 耗时(
Measure-Command、Ms列)因机器和运行而异;只有比例和数量级有意义。 Trace-Command的输出已缩短:去掉了时间戳、DEBUG: ParameterBinding Information: 0 :前缀以及 Import-Csv/Select-Object 的绑定行。- 生产案例是常见事故的综合;其中的机制已复现,周边故事没有。
- 动画对绑定做了简化:省略了动态参数、延迟绑定脚本块,以及跨参数集位置绑定的确切顺序。