8

Can PowerShell Parameters Belong To Multiple Parameter Sets?

 3 years ago
source link: https://thomasrayner.ca/can-powershell-parameters-belong-to-multiple-parameter-sets/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Can PowerShell Parameters Belong To Multiple Parameter Sets?

Say you’ve got a function that takes three parameters: Username, ComputerName and SessionName, but you don’t want someone to use ComputerName and SessionName at once. You decide to put them in separate parameter sets. Awesome, except you want Username to be a part of both parameter sets and it doesn’t look like you can specify more than one.

This will generate an error:

function Do-Thing {
    [CmdletBinding()]
    param (
    [Parameter( ParameterSetName = 'Computer','Session' )][string]$Username,
    [Parameter( ParameterSetName = 'Computer' )][string]$ComputerName,
    [Parameter( ParameterSetName = 'Session' )][PSSession]$SessionName
    )
# Other code
}

So how do you make a parameter a member of more than one parameter set? You need more [Parameter()] qualifiers.

function Do-Thing {
    [CmdletBinding()]
    param (
    [Parameter( ParameterSetName = 'Computer' )]
    [Parameter( ParameterSetname = 'Session' )]
    [string]$Username,

    [Parameter( ParameterSetName = 'Computer' )][string]$ComputerName,
    [Parameter( ParameterSetName = 'Session' )][PSSession]$SessionName
    )
# Other code
}

They chain together and you now $Username is a part of both parameter sets.

Written on June 14, 2017

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK