PowerShell mandatory parameter depends on another parameter

こ雲淡風輕ζ 提交于 2019-11-30 08:06:06

问题


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.


回答1:


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:

http://blogs.msdn.com/b/powershell/archive/2008/12/23/powershell-v2-parametersets.aspx

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"



回答2:


You can also use a dynamic parameter:

New way to create a dynamic parameter



来源:https://stackoverflow.com/questions/13533763/powershell-mandatory-parameter-depends-on-another-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!