0

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?

3
  • 1
    Yes that is the correct way, but you better use the AST parser, see: Is there a way in PowerShell to get the default value of a script parameter? Commented Mar 28, 2023 at 7:18
  • 1
    How did that not show up when I searched for "powershell output default value of parameter" I have no idea, but that definitely looks like a better way of finding it :) In my case I already have the module loaded so I use ::ParseInput instead of ::ParseFile which seems to give me the correct output. Thanks for the help!! Commented Mar 28, 2023 at 7:26
  • 1
    I knew the issue existed already and I also know that the StackOverflow search doesn't always find where I am looking for either. Therefore I often use just google instead: PowerShell get default parameter site:stackoverflow.com Commented Mar 28, 2023 at 7:33

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.