Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Gets the parameters for a command from the default parameter set
function Get-CommandParameter {
param (
[Parameter(Mandatory = $true)]
[String]$Command,
[Switch]$GetDefaultValues
)
$commonParameters = ([System.Management.Automation.Internal.CommonParameters]).GetProperties().Name
$shouldProcessParameters = ([System.Management.Automation.Internal.ShouldProcessParameters]).GetProperties().Name
$defaultParams = $commonParameters + $shouldProcessParameters
# Get command information and go through each parameter
try {
$commandInfo = Get-Command $Command -ErrorAction Stop
if ($commandInfo) {
if ($commandInfo.ParameterSets.Count -eq 1) {
$parameterSetName = $commandInfo.ParameterSets[0].Name
}
else {
$parameterSetName = $commandInfo.ParameterSets.Where{ $_.IsDefault }.Name
}
$parameters = $commandInfo.ParameterSets.Where{ $_.Name -eq $parameterSetName }.Parameters |
Where-Object {
$_.Name -notin $defaultParams -and
-not $_.Attributes.Where{
$_ -is [Parameter] -and
-not $_.ParameterSetName -eq $parameterSetName }.DontShow
} |
Select-Object *, DefaultValue, @{n = 'ValidValues'; e = {
if ($validateSet = $_.Attributes | Where-Object { $_ -is [System.Management.Automation.ValidateSetAttribute] }) {
$validateSet.ValidValues
}
elseif ($_.ParameterType.BaseType -eq [Enum]) {
[Enum]::GetNames($_.ParameterType)
}
}
}
if ($GetDefaultValues) {
if ($commandInfo.CommandType -eq 'Cmdlet') {
$typeInstance = New-Object $commandInfo.ImplementingType
foreach ($parameter in $parameters) {
if ($null -ne $typeInstance.($parameter.Name)) {
$parameter.DefaultValue = $typeInstance.($parameter.Name)
}
}
}
elseif ($commandInfo.CommandType -in 'Function', 'ExternalScript') {
$defaultValues = @{}
foreach ($parameter in $commandInfo.ScriptBlock.Ast.Body.ParamBlock.Parameters) {
if ($parameter.DefaultValue) {
try {
$defaultValues.($parameter.Name.VariablePath.UserPath) = $parameter.DefaultValue.SafeGetValue()
}
catch {
# Ignore errors raised by this
}
}
}
foreach ($parameter in $parameters) {
if ($defaultValues.ContainsKey($parameter.Name)) {
$parameter.DefaultValue = $defaultValues.($parameter.Name)
}
}
}
}
$parameters
}
}
catch {
throw
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment