PowerShell函数开发实战

基础函数结构

1
2
3
4
5
6
function Get-ServerStatus {
param(
[string]$ComputerName
)
Test-Connection $ComputerName -Count 1 -Quiet
}

高级参数验证

1
2
3
4
5
6
7
8
9
10
11
12
function New-UserAccount {
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[Parameter(Mandatory=$true)]
[ValidatePattern('^[a-zA-Z]{3,8}$')]
[string]$UserName,

[ValidateSet('Standard','Admin')]
[string]$Role = 'Standard'
)
# 创建逻辑
}

管道输入处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function Process-FileData {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
[System.IO.FileInfo]$File
)
process {
[PSCustomObject]@{
Name = $File.Name
Size = $File.Length
Hash = (Get-FileHash $File.FullName).Hash
}
}
}

函数最佳实践

  1. 使用注释式帮助系统
  2. 实现ShouldProcess确认机制
  3. 合理设置输出类型
  4. 保持函数功能单一化