从特定参数集中获取所有参数

Get all parameters from specific parameter sets

我在从特定参数集中获取参数时遇到一些问题。我已经通过获取所有参数并将 $parDetails.Name.Contains("FileAttachment") 用作 if 语句来解决它。

我想要的是从特定参数集中获取参数。

有人可以帮我解决这个问题吗?下面是我目前使用的代码。

$CommandName = $PSCmdlet.MyInvocation.InvocationName
$ParameterList = (Get-Command -Name $CommandName).Parameter

foreach ($key in $ParameterList.keys) {
    Write-Verbose "Starting loop for $key"
    $parDetails = Get-Variable -Name $key
}

这是一个在特定参数集中(或所有参数集中)查找参数的脚本。它应该能满足您的需求。

$commandName='Get-ChildItem'
$ParameterSetToMatch='LiteralItems'

$ParameterList = (Get-Command -Name $commandName).Parameters.Values

foreach($parameter in $parameterList){
    $parameterSets=$parameter.ParameterSets.Keys
    if($parameterSets -contains '__AllParameterSets'){
        write-host "$($parameter.Name) is in __AllParameterSets"
    } elseif ($parameterSets -contains $parameterSetToMatch ){
        write-host "$($parameter.Name) is in $parameterSetToMatch"
    }
}

如果您只需要参数集中的具体项目,这里有一个较短的版本:

$commandName='Get-ChildItem'
$ParameterSetToMatch='Items'
$parameterlist |  
    Where-object {$_.ParameterSets.Keys -contains $ParameterSetToMatch} | 
     select-object Name

使用 PSv4+ 语法:

# Sample cmdlet and parameter set to inspect.
# To determine all parameter-set names for a given cmdlet, use:
#  (Get-Command $commandName).ParameterSets.Name
$cmd = 'Get-Item'
$paramSet = 'Path'

# Get all parameters associated with the specified parameter set.
$paramsInSet = (Get-Command $cmd).ParameterSets.Where({$_.Name -eq $paramSet}).Parameters

# Output the names of all parameters in the set.
$paramsInSet.Name

以上结果:

Path
Filter
Include
Exclude
Force
Credential
Verbose
Debug
ErrorAction
WarningAction
InformationAction
ErrorVariable
WarningVariable
InformationVariable
OutVariable
OutBuffer
PipelineVariable