动态参数机制
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
| function Get-EnvironmentData { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [string]$EnvironmentName ) dynamicparam { $paramDictionary = New-Object Management.Automation.RuntimeDefinedParameterDictionary if ($EnvironmentName -eq 'Production') { $attribute = [System.Management.Automation.ParameterAttribute]@{ Mandatory = $true HelpMessage = "生产环境专属参数" } $param = New-Object Management.Automation.RuntimeDefinedParameter( 'ProductionKey', [string], $attribute ) $paramDictionary.Add('ProductionKey', $param) } return $paramDictionary } }
|
参数集应用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| function Set-SystemConfiguration { [CmdletBinding(DefaultParameterSetName='Basic')] param( [Parameter(ParameterSetName='Basic', Mandatory=$true)] [string]$BasicConfig, [Parameter(ParameterSetName='Advanced', Mandatory=$true)] [string]$AdvancedConfig, [Parameter(ParameterSetName='Advanced')] [ValidateRange(1,100)] [int]$Priority ) }
|
最佳实践
- 使用Parameter属性定义清晰的参数关系
- 为复杂场景设计参数集
- 通过dynamicparam实现条件参数
- 保持参数命名的语义清晰
```powershell
function Invoke-CustomOperation {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
[ValidateScript({
if ($_.OperationType -notin ‘Read’,’Write’) {
throw “无效的操作类型”
}
$true
})]
[object]$InputObject
)
# 管道参数处理逻辑
}