PowerShell mandatory parameter depends on another parameter

simon picture simon · Nov 23, 2012 · Viewed 35.2k times · Source

I have a PowerShell function which changes the registry key values. Code:

param(
    [Parameter()] [switch]$CreateNewChild,
    [Parameter(Mandatory=$true)] [string]$PropertyType
)

It has a parameter, "CreateNewChild", and if that flag is set, the function will create the key property, even if it wasn't found. The parameter "PropertyType" must be mandatory, but only if "CreateNewChild" flag has been set.

The question is, how do I make a parameter mandatory, but only if another parameter has been specified?

OK, I've been playing around with it. And this does work:

param(
  [Parameter(ParameterSetName="one")]
  [switch]$DoNotCreateNewChild,

  [string]$KeyPath,

  [string]$Name,

  [string]$NewValue,

  [Parameter(ParameterSetName="two")]
  [switch]$CreateNewChild,

  [Parameter(ParameterSetName="two",Mandatory=$true)]
  [string]$PropertyType
)

However, this means that $KeyPath, $Name and $NewValue are not mandatory any more. Setting "one" parameter set to mandatory breaks the code ("parameter set cannot be resolved" error). These parameter sets are confusing. I'm sure there is a way, but I can't figure out how to do it.

Answer

Rex Hardin picture Rex Hardin · Nov 23, 2012

You could group those parameters by defining a parameter set to accomplish this.

param (
    [Parameter(ParameterSetName='One')][switch]$CreateNewChild,
    [Parameter(ParameterSetName='One',Mandatory=$true)][string]$PropertyType
)

Reference:

https://devblogs.microsoft.com/powershell/powershell-v2-parametersets

http://blogs.technet.com/b/heyscriptingguy/archive/2011/06/30/use-parameter-sets-to-simplify-powershell-commands.aspx

--- Update ---

Here's a snippet that mimics the functionality you're looking for. The "Extra" parameter set will not be processed unless the -Favorite switch is called.

[CmdletBinding(DefaultParametersetName='None')] 
param( 
    [Parameter(Position=0,Mandatory=$true)] [string]$Age, 
    [Parameter(Position=1,Mandatory=$true)] [string]$Sex, 
    [Parameter(Position=2,Mandatory=$true)] [string]$Location,
    [Parameter(ParameterSetName='Extra',Mandatory=$false)][switch]$Favorite,      
    [Parameter(ParameterSetName='Extra',Mandatory=$true)][string]$FavoriteCar
)

$ParamSetName = $PsCmdLet.ParameterSetName
    
Write-Output "Age: $age"
Write-Output "Sex: $sex"
Write-Output "Location: $Location"
Write-Output "Favorite: $Favorite"
Write-Output "Favorite Car: $FavoriteCar"
Write-Output "ParamSetName: $ParamSetName"