Saturday, December 19, 2020

PowerShell: Assigning the No-Parameter-Specified case to a Parameter Set

 

PowerShell parameter sets allow cmdlet parameters to be grouped so that only certain parameters can be used in combination (see PowerShell: Cmdlet Parameter Sets). When parameter sets are used, there needs to be a mechanism for specifying what parameter set is associated when there is no parameter specified when invoking a Cmdlet. The DefaultParameterSetName property of the CmdletBinding attribute (see About Functions CmdletBindingAttribute) identifies which parameter set is the default parameter set and hence the parameter set invoked when no parameter is specified to a cmdlet.

To demonstrate the issue consider a cmdlet, CreateArtifacts.ps1, which is used during build to create artifacts. The parameters and parameter sets for this cmdlet are defined as follows:


param
(
 [Parameter(ParameterSetName='Debug')]
 [switch] $IsDebug,
 [Parameter(ParameterSetName='Release')]
 [switch] $IsRelease
)

Write-Host 'Hi mom, I miss you.'

There is no way to identify in the previous script whether the parameter set named, Debug, or the parameter set named, Release, should be processed if no parameter is specified to the CreateArtifacts.ps1 cmdlet. When the script is invoked from Visual Studio code the following message is displayed:



Assigning a value of Release to the DefaultParameterSetName property of the CmdletBinding attribute specifies that the default parameter set is named, Release:

[CmdletBinding(DefaultParameterSetName='Release')]
param
(
 [Parameter(ParameterSetName='Debug')]
 [switch] $IsDebug,
 [Parameter(ParameterSetName='Release')]
 [switch] $IsRelease
)

Write-Host 'Hi mom, I miss you.'

Invoking the the CreateArtifacts.ps1 cmdlet as showing above with the DefaultParameterSetName specified allows the script to run successfully even when no parameter is specified when the script is invoked:





No comments :

Post a Comment