Group parameter (set?) requiring one of the parameters

天大地大妈咪最大 提交于 2020-01-06 08:10:39

问题


I'm trying to set up parameters where one of three set of parameters are required and include an integer followed by a colon;

-year:n  
-month:n  
-day:n

Can't quite wrap my head around parameter sets via Microsoft Docs and need help setting this up, please.

In the end the parameter will be used for Robocopy's MinAge parameter where if -month:2 is used, I'll strip out the 2, multiply by 30.4167 (average day in month) and insert /MinAge:60.8334 as the Robocopy parameter. I have the last part down, just not the parameter part.


回答1:


I think this can explain a bit. The function below uses three parameters, all having a different parmeter set name.

function Get-MinAge {
    [CmdletBinding(DefaultParameterSetName = 'ByDays')]
    param (
        [Parameter(Mandatory = $true, ParameterSetName = 'ByYears', Position = 0)]
        [int]$Years,
        [Parameter(Mandatory = $true, ParameterSetName = 'ByMonths', Position = 0)]
        [int]$Months,
        [Parameter(Mandatory = $true, ParameterSetName = 'ByDays', Position = 0)]
        [int]$Days
    )

    switch ($PSCmdlet.ParameterSetName) {
        'ByYears'  { $minage = $Years * 365.2422 ; break}  # average year length
        'ByMonths' { $minage = $Months * 30.4167 ; break } # average month length
        'ByDays'   { $minage = $Days }
    }
    # return the parameter for robocopy
    # wrapping inside quotes makes sure your Windows locale does not change the decimal point
    '/MinAge:{0}' -f "$minage"
}

Using this within the ISE editor will allow for only one of the three parameters. The function also has a DefaultParameterSetName, meaning that if you dont specify the parameter name, the defauld set is used (in this case the 'ByDays' set).

Use it like so:

Get-MinAge -Years 2   --> "/MinAge:730.4844"
Get-MinAge -Months 2  --> "/MinAge:60.8334"
Get-MinAge -Days 2    --> "/MinAge:2"
Get-MinAge 2          --> "/MinAge:2"

Hope that helps



来源:https://stackoverflow.com/questions/58769708/group-parameter-set-requiring-one-of-the-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!