簡體   English   中英

PowerShell 強制參數取決於另一個參數

[英]PowerShell mandatory parameter depends on another parameter

我有一個 PowerShell 函數可以更改注冊表項值。 代碼:

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

它有一個參數“CreateNewChild”,如果設置了該標志,該函數將創建鍵屬性,即使它沒有被找到。 參數“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 不再是強制性的。 將“一個”參數集設置為強制會破壞代碼( “參數集無法解析”錯誤)。 這些參數集令人困惑。 我確定有辦法,但我不知道該怎么做。

您可以通過定義參數集來對這些參數進行分組以完成此操作。

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

參考:

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

- - 更新 - -

這是一個模仿您正在尋找的功能的片段。 除非調用 -Favorite 開關,否則不會處理“額外”參數集。

[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"

您還可以使用動態參數:

創建動態參數的新方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM