1

How do I allow the option to run a PowerShell script that leverages parameter sets to run without passing any parameters? Is this possible?

param(

  [Parameter(Mandatory=$true,HelpMessage="GenSecureFile used to generate secure password file.",     ParameterSetName = 'GenSecureFile')]
  [switch]$GenSecureFile,

  [Parameter(Mandatory=$true,HelpMessage="GenSettingsFile used to generate settings file.", ParameterSetName = 'GenSettingsFile')]
  [switch]$GenSettingsFile

)

Attempted to use a default parameter but this does not let you run the script with no parameters.

1
  • This is possible but looking at your param block you have 2 switch parameters in different sets and these are the only 2 parameters. This leads be to believe your param should be reduced to only 1 [string] parameter that uses a [ValidateSet(...)] attribute decoration Commented Dec 30, 2022 at 17:40

1 Answer 1

2

For this to work properly the parameter being declared as DefaultParameterSetName shouldn't be flagged as Mandatory and possibly be set to $true which wouldn't make sense for a switch Parameter. switch Parameters are meant to be optional (should not be Mandatory) and should not have a default value.

For Example:

function Test-Parameter {
    [CmdletBinding(DefaultParameterSetName = 'GenSecureFile')]
    param(
        [Parameter(ParameterSetName = 'GenSecureFile')]
        [switch] $GenSecureFile = $true,

        [Parameter(Mandatory, ParameterSetName = 'GenSettingsFile')]
        [switch] $GenSettingsFile
    )

    end {
        $PSCmdlet.ParameterSetName
    }
}

Test-Parameter

What you should do instead is have only one parameter that uses a ValidateSet Attribute Declaration, by doing so there wouldn't be a need for Parameter Sets.

For Example:

function Test-Parameter {
    [CmdletBinding()]
    param(
        [Parameter()]
        [ValidateSet('SecureFile', 'SettingsFile')]
        [string] $Gen = 'SecureFile'
    )

    end {
        if($Gen -eq 'SecureFile') {
            # do something here when `SecureFile`
            return
        }

        # do something here when `SettingsFile`
    }
}

Test-Parameter
Sign up to request clarification or add additional context in comments.

2 Comments

it would seem to me that the END block is un-necessary? Is there something I'm missing?
@RetiredGeek It is un-necessary but also a preference. I like to be explicit. You're correct tho, a function or scriptblock with undeclared blocks assumes end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.