PowerShell mandatory parameter depends on another parameter

后端 未结 2 652
花落未央
花落未央 2020-12-16 12:02

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

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


        
相关标签:
2条回答
  • 2020-12-16 12:31

    You can also use a dynamic parameter:

    New way to create a dynamic parameter

    0 讨论(0)
  • 2020-12-16 12:46

    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:

    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

    --- 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"
    
    0 讨论(0)
提交回复
热议问题