约 2230 字

约 11 分钟

#特性(Attributes)

#简介

特性(Attribute)是写在方括号 [] 中的元数据,用来修饰函数、参数、变量或类成员。PowerShell 利用特性实现高级函数、参数验证和输出类型声明,运行时和工具可以通过反射读取这些信息。

#CmdletBinding

在函数或脚本块上添加 [CmdletBinding()],可以把它变为高级函数,从而支持 -Verbose、-Debug、-ErrorAction 等通用参数:

function Get-Square {
    [CmdletBinding()]
    param([int]$Number)
    $Number * $Number
}

Get-Square -Number 5 -Verbose

高级函数还可以使用 begin、process、end 命名块处理管道输入。

#参数特性

参数特性写在 param 块中的参数声明之前:

特性说明
[Parameter(Mandatory)]参数必填,未提供时提示输入
[Parameter(Position = 0)]指定位置参数顺序
[Parameter(ValueFromPipeline)]从管道接收输入
[ValidateSet()]限制可选值
[ValidateRange()]限制数值范围
[ValidatePattern()]用正则表达式校验字符串
function Get-Square {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, Position = 0)]
        [ValidateRange(0, 1000)]
        [int]$Number
    )
    $Number * $Number
}

验证特性在函数体执行前生效。例如 Get-Square -Number 1001 会因为超出范围而报错,函数体不会运行。

#ValidateSet、ValidateRange 与 ValidatePattern

function New-Report {
    param(
        [ValidateSet('Html', 'Json', 'Csv', IgnoreCase = $true)]
        [string]$Format,

        [ValidateRange(1, 65535)]
        [int]$Port,

        [ValidatePattern('^[a-z][a-z0-9-]{2,15}$')]
        [string]$Name
    )

    "生成 $Format 报告,端口 $Port,名称 $Name"
}

需要更灵活的自定义验证时,可以使用 [ValidateScript({ ... })],脚本块返回 $true 表示通过。

#自定义特性简介

自定义特性是继承自 System.Attribute 的类。类名以 Attribute 结尾时,使用时可以省略后缀:

class AuthorAttribute : System.Attribute {
    [string]$Name

    AuthorAttribute([string]$name) {
        $this.Name = $name
    }
}

[Author('Alice')]
function Test-Thing {
    'ok'
}

自定义特性本身不会改变 PowerShell 的执行行为,通常需要配合工具或模块读取元数据。特性类必须在应用之前定义。

#注意事项

  • 验证特性失败时不会进入函数体。
  • [Parameter()] 通常与 [CmdletBinding()] 一起使用,使函数行为更明确。

#推荐阅读

更新: 2026/11/2

作者: planc

创建: 2026/11/2