PowerShell强制参数取决于另一个参数 [英] PowerShell mandatory parameter depends on another parameter

查看:121
本文介绍了PowerShell强制参数取决于另一个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PowerShell函数,该函数可以更改注册表项的值.代码:

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

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

它有一个参数"CreateNewChild",并且如果设置了该标志,该函数将创建key属性,即使找不到该属性也是如此.参数"PropertyType"必须是必需的,但前提是已设置"CreateNewChild"标志.

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
)

但是,这意味着$ KeyPath,$ Name和$ NewValue不再是必需的.将一个"参数设置为强制性会破坏代码(无法解析参数集" 错误).这些参数集令人困惑.我敢肯定有办法,但是我不知道怎么做.

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.

推荐答案

您可以通过定义参数集来对这些参数进行分组.

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
)

参考:

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

-更新---

这是一个模仿您正在寻找的功能的代码段.除非调用-Favorite开关,否则不会处理额外"参数集.

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"

这篇关于PowerShell强制参数取决于另一个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆