The answer from @mklement0 is very helpful. https://stackoverflow.com/a/42699260/447901
I wanted to write a script that will produce all Github configuration settings. The PowerShellForGitHub module function Get-GitHubConfiguration only reports one at a time and you must already know the name of the setting. The settings supported vary across versions. This code gets the setting names based on the ValidateSet() for the $Name parameter and produces them all.
The question is... Is it important to test that the Attribute is of type [System.Management.Automation.ValidateSetAttribute]? What other type might it be?
Both of the $Names =
lines produce the same array.
[CmdletBinding()]
#$Names = (Get-Command -Name 'Get-GitHubConfiguration').Parameters.Name.Attributes.ValidValues
$Names = ((Get-Command -Name 'Get-GitHubConfiguration').Parameters.Name.Attributes |
Where-Object { $_ -is [System.Management.Automation.ValidateSetAttribute] }).ValidValues
foreach ($Name in $Names) {
[PSCustomObject]@{
Name = $Name
Value = Get-GitHubConfiguration -Name $Name
}
}
CodePudding user response:
Assuming you're using this Get-GitHubConfiguration
implementation, it is the -Name
parameter you're interested in, and the following command extracts the values defined for its [ValidateSet]
attribute:
$names =
(Get-Command Get-GitHubConfiguration).
Parameters['Name'].
Attributes.Where({ $_ -is [ValidateSet] }).
ValidValues
$names
then contains an array of strings (@('ApiHostName', 'ApplicationInsightsKey', ...)
)
PowerShell offers several attributes for validating arguments passed to parameters, but only the following allow discovery of a discrete set or a range of permissible values:
[ValidateSet]
, both with statically enumerated values, as in the case at hand, and - in PowerShell (Core) 7 only - via a helper class that implements theIValidateSetValuesGenerator
interface for dynamic generation of the permissible values.[ValidateRange]
for limiting arguments to a range of values, defined via inclusive endpoints.