简体   繁体   中英

Powershell parameter condition

function test{
    [cmdletBinding()]
    param(
        [Parameter(Position=0,Mandatory=$true)] [string]$Age, 
        [Parameter(Position=1,Mandatory=$true)] [string]$Sex, 
        [Parameter(Position=2,Mandatory=$true)] [string]$Location,
        [Parameter(Mandatory=$false)][ValidateSet("True","False")][string]$Favorite
        [Parameter(Mandatory=$false)[string]$FavoriteCar
    )

}

let's say first three parameters are required but not the 4th and 5th. For $Favorite, I can only pass true or false but by default it would be $false but if I pass true, I want $favoriteCar to be set to $true.

function test{
    [cmdletBinding(DefaultParameterSetName = 'all')]
    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=$true)][bool]$Favorite,
        [Parameter(ParameterSetName='Extra',Mandatory=$true)][string]$FavoriteCar
    )


    if ($PSCmdlet.ParameterSetName -eq 'extra')
    {
        if($Favorite)
        {
            Write-Host ('age:{0}, sex: {1}, location: {2}, favcar: {3}' -f $age ,$sex, $Location,$FavoriteCar)
        }
        else
        {
            'nothing'
        }

    }
    else
    {
        Write-Host ('age:{0}, sex: {1}, location: {2}' -f $age ,$sex, $Location)
    }

}

you dont need to do [ValidateSet("True","False")][switch] because [switch] always evaluates to a boolean. true if present, else false

If no default parameter set name is specified, PS would default to whichever ParameterSetName it finds on a parameter which in this case is extra and will prompt you for the favcar parameter which is mandatory. Of course there is no all parameterset specified but we set it so PS dosent attempt to run the extra ParameterSet by default.

EDIT

in the below command since parameters $favorite\\$favoritecar are not used PS will not prompt you for any values.

test -Age 10 -Sex female -Location Moon

Output :

age:10, sex: female, location: Moon

the below will force PS to use the parameterset 'extra' and prompt you to enter a value for the parameter $favoritecar because it is mandatory in the parameterset 'extra'.

test -Age 10 -Sex female -Location Moon -favorite $true

the below will still prompt you for the $favoritecar parameter because it is mandatory however nothing will be processed because of the if condition in the code.

test -Age 10 -Sex female -Location Moon -Favorite $false -FavoriteCar Ferrari

Output :

nothing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM