是否可以向系统参数添加属性?
e.g。说我有一个支持分页的功能:
function Get-MyPage {
[CmdletBinding(SupportsPaging = $true)]
param (
[Parameter(Mandatory)]
[string]$Something
)
process {
#...
}
}
我可以为$Something
参数添加别名,或者像这样添加验证:
[Alias('Thing')]
[ValidateSetAttribute('A','B','C')]
[string]$Something
但是,是否可以使用通过CmdletBinding / SupportsPaging添加的“系统参数”来执行此操作?
即。鉴于我没有明确定义First
参数?
[Alias('PageSize')]
[ValidateRange(1, 250)]
#[int]$First #This parameter exists because SupportsPaging = $true
尝试:
[PSAlias]$FirstAlias = New-Object 'PSAlias' -ArgumentList @('PageSize', 'First', ([string].Name))
(Get-Command -Name 'Get-MyPage').Parameters['First'].Aliases.Add($FirstAlias)
(Get-Command -Name 'Get-MyPage').Parameters['First'].Aliases #this shows it's been successfully added
Get-MyPage "hello" -Skip 3 -IncludeTotalCount -PageSize 4 #this shows it doesn't work
#Get-MyPage : A parameter cannot be found that matches parameter name 'PageSize'.
(Get-Command -Name 'Get-MyPage').Parameters['First'].Aliases.Clear()
(Get-Command -Name 'Get-MyPage').Parameters['First'].Aliases.Add('PageSize')
Get-MyPage "hello" -PageSize 2 -Skip 3 -IncludeTotalCount
#Get-MyPage : A parameter cannot be found that matches parameter name 'PageSize'
(Get-Command -Name 'Get-MyPage').Parameters['First'].Attributes.Add((New-Object 'System.Management.Automation.AliasAttribute' -ArgumentList 'First'))
#Get-MyPage : A parameter cannot be found that matches parameter name 'PageSize'.
用于上述
的完整Cmdlet代码function Get-MyPage {
[CmdletBinding(SupportsPaging = $true)]
param (
[Parameter(Mandatory)]
[string]$Something
)
process {
[hashtable]$splat = @{}
if ($PSCmdlet.PagingParameters.Skip) {$splat.Add('Skip', $PSCmdlet.PagingParameters.Skip)}
if ($PSCmdlet.PagingParameters.First -ne [System.UInt64]::MaxValue) {$splat.Add('First', $PSCmdlet.PagingParameters.First)}
$Something.ToCharArray() | select @splat
}
end {
if ($PSCmdlet.PagingParameters.IncludeTotalCount) { $PSCmdlet.PagingParameters.NewTotalCount($Something.ToCharArray().Count, 1.0)}
}
}