您如何以编程方式获取所有常用参数的列表?

How do you programmatically get a list of all common parameters?

Powershell Cmdlet 继承了一堆 common parameters。我编写的一些 cmdlet 以谓词结束,这些谓词取决于实际绑定的参数。这通常会导致过滤掉公共参数,这意味着您需要一个公共参数名称列表。

我还希望不同版本的 powershell 的通用参数列表有所不同。

所有这些都归结为这个问题:

如何以编程方式确定常用参数列表?

像这样:

function Get-CommonParameterNames
{
    [CmdletBinding()]
    param()
    $MyInvocation.MyCommand.Parameters.Keys
}

这些静态属性呢?

[System.Management.Automation.PSCmdlet]::CommonParameters
[System.Management.Automation.PSCmdlet]::OptionalCommonParameters

现有的公共参数是两个列表的组合:

CommonParameters: Lists the common parameters that are added by the PowerShell engine to any cmdlet that derives from PSCmdlet.

OptionalCommonParameters: Lists the common parameters that are added by the PowerShell engine when a cmdlet defines additional capabilities (SupportsShouldProcess, SupportsTransactions)

即它们都可以存在,但可选的只有在 cmdlet 支持它们时才存在。有关详细信息,请参阅 Cmdlet Class