Home > Software engineering >  How to do conditional mandatory parameters in powershell?
How to do conditional mandatory parameters in powershell?

Time:01-25

ex: suppose I have

[Parameter(Mandatory=$true)]
[ValidateSet("UP","DOWN")]
$Direction,

[Parameter(Mandatory=$true)]
[string]$AssertBytes,

[ValidateScript({
    if($_ -notmatch "(\.json)"){
        throw "The file specified in the path argument must be of type json"
    }
    return $true 
})]
$JsonMappingsFilePath,

If I have $AssertBytes equal true then I want $JsonMappingsFilePath to be mandatory. Otherwise I want it ignored.

This does not seem to work :

[Parameter(Mandatory=$true)]
[ValidateSet("UP","DOWN")]
$Direction,

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

[Parameter(ParameterSetName='AssertBytes', Mandatory=$False)]
[ValidateScript({
    if($_ -notmatch "(\.json)"){
        throw "The file specified in the path argument must be of type json"
    }
    return $true 
})]
$JsonMappingsFilePath,

CodePudding user response:

Make AssertBytes a member of two distinct parameter sets - one in which it's mandatory, another in which it is not - the use the CmdletBinding attribute to specify the one in which the parameter is optional as the default parameter set:

[CmdletBinding(DefaultParameterSetName = 'NoAssertBytes')]
param(
    [Parameter(Mandatory=$true)]
    [ValidateSet("UP","DOWN")]
    $Direction,

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

    [Parameter(ParameterSetName='AssertBytes', Mandatory=$True)]
    [Parameter(ParameterSetName='NoAssertBytes', Mandatory=$False)]
    [ValidateScript({
        if($_ -notmatch "(\.json)"){
            throw "The file specified in the path argument must be of type json"
        }
        return $true 
    })]
    $JsonMappingsFilePath
)
  • Related