Search code examples
c#powershelldocumentation-generation

How to provide default value for a parameter in PowerShell help for compiled cmdlets


Terminology: I use scripted cmdlet to mean a cmdlet written in PowerShell and compiled cmdlet to mean a cmdlet written in C#.

With scripted cmdlets--as of PowerShell V3--it is straightforward to fill in the "Default Value" slot in PowerShell help output. For example, this function...

function Do-Stuff([parameter(Mandatory)][string]$Provider="abc") {...}

will allow this command...

Get-Help Do-Stuff -parameter Provider

to return this output...

-Provider <string>
    Required?                    true
    Position?                    1
    Default value                abc
    Accept pipeline input?       false
    Accept wildcard characters?  false

Writing a compiled cmdlet you can attach the same attributes (e.g. "Mandatory") but the default value is somewhat a special case. Since a PowerShell parameter is typically done with an auto-implemented property in C# and (prior to C# 6.0) auto-implemented properties in C# do not even support initializers, I suspect it may not be possible to fill in that Default Value slot. (Except for SwitchParameters, which actually do have the Default Value filled out with "False", naturally enough.)

So for a compiled cmdlet, is there a way to fill out that Default Value slot in help output by some form of C# code instrumentation? Currently I am using C# 4.0 but if not possible with 4.0, then is it possible with 6.0?


Solution

  • The answer to my question is dependent upon the utility used to generate the documentation, of course. As I mentioned in a comment, I am using XmlDoc2CmdletDoc. After further experimentation (and reviewing the source) I discovered that it does, in fact, support default values. All one has to do is provide an initial value for a property via a backing field, and that value will appear in the generated help as the default value. Example:

    private int _quantity = 25;
    
    public int Quantity
    {
        get { return _quantity; }
        set { _quantity = value; }
    }
    

    So even if the backing field is unneeded (as in this example), it needs to be introduced if you want the default value of 25 to be documented.