PowerShell 技能连载 - 高级函数开发技巧

参数验证体系

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function Get-SystemInfo {
[CmdletBinding()]
param(
[Parameter(Mandatory,ValueFromPipeline)]
[ValidatePattern('^[a-zA-Z]')]
[string[]]$ComputerName,

[ValidateSet('CPU','Memory','Disk')]
[string]$Category = 'CPU'
)
begin {
$results = @()
}
process {
foreach ($computer in $ComputerName) {
$data = [PSCustomObject]@{
Computer = $computer
Status = 'Online'
$Category = (Get-CimInstance -ClassName Win32_$Category)
}
$results += $data
}
}
end {
$results
}
}

管道输入优化

1
2
3
4
5
6
# 支持三种输入方式
'Server01','Server02' | Get-SystemInfo -Category Memory

Get-Content servers.txt | Get-SystemInfo

Get-SystemInfo -ComputerName (Import-Csv -Path datacenter.csv).Name

最佳实践:

  • 使用begin/process/end块处理流水线
  • 通过ValidatePattern限制输入格式
  • 利用ValueFromPipeline属性支持管道
  • 添加帮助注释增强可维护性

PowerShell 技能连载 - 高级函数开发技巧

http://blog.vichamp.com/2024/07/12/powershell-functions/

作者

吴波

发布于

2024-07-12

更新于

2025-03-25

许可协议

评论