2012-11-23 58 views
12

我有一個PowerShell函數可以改變註冊表鍵值。代碼:PowerShell強制性參數取決於其他參數

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

它有一個參數「CreateNewChild」,如果該標誌被設置,該函數將創建關鍵屬性,即使它wan't發現。參數「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不再是強制性的。將「一個」參數設置爲強制中斷代碼(參數集不能解析錯誤)。這些參數集令人困惑。我敢肯定,有一種方法,但我不知道如何去做

回答

21

你可以通過定義一個參數集來完成這些參數。

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" 
+0

我想這一點,這裏是代碼: '參數( [參數(位置= 0,強制= $真) ] [string] $ KeyPath, [參數(Position = 1,Mandatory = $ true)] [string] $名稱, [Parameter(Position = 2,Mandatory = $ true)] [string] $ NewValue, [Parameter (ParameterSetName =「One」)] [switch] $ CreateNewChild, [Parameter(ParameterSetName =「 One「,Mandatory = $ true)] [string] $ PropertyType ) '但是,這是行不通的。當試圖執行以下操作: 'Set-RegistryKeyPropertyValue -KeyPath $ path -Name $ name -NewValue 0' 它要求我提供$ PropertyType的值,因爲它是必需的 – lime

+0

對不起,我應該更具體。我在上面的答案中增加了一個更好的例子。 :) –

+0

是的,這正是我一直在尋找的!謝謝! p.s.我還沒有嘗試使「$ Favorite」爲強制性的一個選項= $ false,我認爲這是默認情況下是錯誤的。這個參數設置的邏輯很奇怪... – lime

-2

你也可以使用動態參數:

new way to create dynamic parameter

+1

只提供一個鏈接到外語論壇根本沒有幫助。請提供一個解決所描述問題的例子。 –

+0

這是一個很好的答案更好的鏈接可用(http://www.powershellmagazine.com/2014/05/29/dynamic-parameters-in-powershell/) –

+0

https://msdn.microsoft.com/powershell/reference /5.1/Microsoft.PowerShell.Core/about/about_Functions_Advanced_Parameters#-47 –