In our last tip we explained how you can hide parameters from IntelliSense. This has a cool side effect that we’d like to point you to today!

PowerShell supports two different types of functions: simple functions and advanced functions. A simple function just exposes the parameters you define. An advanced function also adds all the common parameters. Here are two sample functions:

function Simple
{
    param
    (
        $Name
    )
}

function Advanced
{
    param
    (
        [Parameter(Mandatory)]
        $Name
    )
}

When you run Simple in an editor with IntelliSense, you see just the -Name parameter. When you do the same with Advanced, you also see a bunch of common parameters that are present always.

Whenever you use an attribute (pattern of attributes are [Name(Value)]), PowerShell creates an advanced function, and there is no way for you to exclude the common parameters. What could you do to benefit from the advantages of advanced functions (i.e. mandatory parameters) but still would like to only show your own parameters to the user?

Here is a secret trick. Compare the following two functions:

function Advanced
{
    param
    (
                [Parameter(Mandatory)]
        [string]
        $Name,
        
        [int]
        $Id,
        
        [switch]
        $Force
    )
}

function AdvancedWithoutCommon
{
    param
    (
        [Parameter(Mandatory)]
        [string]
        $Name,
        
        [int]
        $Id,
        
        [switch]
        $Force,
        
        # add a dummy "DontShow" parameter
        [Parameter(DontShow)]
        $Anything
    )
}

When you run the “Advanced” function, you see your own parameters plus the common parameters. When you do the same with “AdvancedWithoutCommon”, you only see your own parameters but still keep the functionality of advanced functions, i.e. the -Name parameter is still mandatory.

The effect is created by adding at least one hidden parameter. Hidden parameters were introduced in PowerShell 5 to facilitate class methods (prevent hidden properties from showing). Since class members don’t show common parameters, the attribute value “DontShow” not only hides that particular member from IntelliSense, it also hides all common parameters.

Which in turn yields to another interesting fact: even though the common parameters are now hidden from IntelliSense, they are still present and can be used:

function Test
{
    param
    (
        [Parameter(Mandatory)]
        [string]
        $Name,
        
        # add a dummy "DontShow" parameter
        [Parameter(DontShow)]
        $Anything
    )
    
    Write-Verbose "Hello $Name"
}
 
PS> Test -Name tom

PS> Test -Name tom -Verbose
VERBOSE:  Hello tom

PS>
 

Twitter This Tip! ReTweet this Tip!

Anonymous