PowerShell必需参数取决于另一个参数

问题描述 投票:16回答:2

我有一个PowerShell函数,它可以更改注册表项值。码:

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

它有一个参数“CreateNewChild”,如果设置了该标志,该函数将创建key属性,即使找不到它也是如此。参数“PropertyType”必须是必需的,但仅限于已设置“CreateNewChild”标志。

问题是,如何强制执行参数,但仅在指定了其他参数的情况下?

好的,我一直在玩它。这确实有效:

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不再是强制性的。将“one”参数设置为必需会中断代码(“参数集无法解析”错误)。这些参数集令人困惑。我确定有办法,但我无法弄清楚如何做到这一点。

powershell parameters dependencies registry flags
2个回答
27
投票

您可以通过定义参数集来对这些参数进行分组以实现此目的。

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

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

---更新---

这是一个模仿您正在寻找的功能的片段。除非调用-Favorite开关,否则不会处理“Extra”参数集。

[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
投票

您还可以使用动态参数:

New way to create a dynamic parameter

© www.soinside.com 2019 - 2024. All rights reserved.