I know that you can get the parameters from a commandlet by running
(Get-Command My-CommandGoesHere).Parameters.Keys
I also know you should be able to get the values for a ValidateSet within a script if you run
(Get-Command My-CommandGoesHere).Parameters["MyParameter"].Attributes.ValidValues
Is it possible to get the default value of a parameter? Suppose I have a commandlet that begins with
param(
[string]$MyVariable = "MyDefaultValue"
)
Is there any way to, outside of this commandlet, get the "MyDefaultValue" somehow? I could do something like
(((Get-Command My-CommandGoesHere).Definition -split "param\(")[1] -split "\)")[0]
but this only works if I have one variable, and that I know what the variable name is. The closest I think I've gotten would be something like
$ParameterName = "MyVariable"
$CommandletDefinition = ((Get-Command My-CommandGoesHere).Definition -split "`n").Trim()
$ParameterStart = $CommandletDefinition.IndexOf("param(")
$ParameterEnd = $CommandletDefinition.IndexOf(")")
$ParameterSection = @()
for ($i=$ParameterStart+1; $i-le $ParameterEnd-1 ;$i++) {
$ParameterSection += $CommandletDefinition[$i]
}
[string]$ParameterValue = [string]($ParameterSection -match $ParameterName)
(($ParameterValue -split "$ParameterName = """)[1] -split """")[0]
But that feels like a really bad workaround to something that should probably be available with a one-liner. Is there a better way to extract the default value from a parameter in a commandlet/module?
PowerShell get default parameter site:stackoverflow.com