powershellparameter-sets

Parameter sets - ensure parameters exist


I'm trying to use Parameter Sets to replicate this functionality:

if (($hostName) -or ($databaseName) -and (!$databasePassword)) {
    throw "If hostName or databaseName specified, you must use databasePassword parameter."
}

Simple example of what I have so far:

[Parameter(Mandatory=$false, ParameterSetName="Test")]
[string]$hostName,

[Parameter(Mandatory=$false, ParameterSetName="Test")]
[string]$databaseName,

[Parameter(Mandatory=$false, ParameterSetName="Test")]
[string]$databasePassword

This is not working. I can supply $hostName without $databasePassword for example, or $dataBasename without $databasePassword and the function runs.

What am I missing?


Solution

  • Make two parameter sets, make $Hostname mandatory in the first, make $DatabaseName optional in the first and mandatory in the other, make $DatabasePassword mandatory in both.

    [CmdletBinding(DefaultParameterSetName='host')]
    Param(
        [Parameter(ParameterSetName='host', Mandatory=$true)]
        [string]$Hostname,
    
        [Parameter(ParameterSetName='host', Mandatory=$false)]
        [Parameter(ParameterSetName='dbname', Mandatory=$true)]
        [string]$DatabaseName,
    
        [Parameter(ParameterSetName='host', Mandatory=$true)]
        [Parameter(ParameterSetName='dbname', Mandatory=$true)]
        [string]$DatabasePassword
    )