Skip to content

Instantly share code, notes, and snippets.

@indented-automation
Last active December 17, 2021 23:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save indented-automation/7b92bc817a985901e57a882fdd19d278 to your computer and use it in GitHub Desktop.
Save indented-automation/7b92bc817a985901e57a882fdd19d278 to your computer and use it in GitHub Desktop.
Gets the parameters for a command from the default parameter set
function Get-CommandParameter {
param (
[Parameter(Mandatory = $true)]
[String]$Command,
[Switch]$GetDefaultValues
)
$defaultParams = @(
[System.Management.Automation.Internal.CommonParameters].GetProperties().Name
[System.Management.Automation.Internal.ShouldProcessParameters].GetProperties().Name
[System.Management.Automation.Internal.TransactionParameters].GetProperties().Name
)
# 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
}
}
@ninmonkey
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment