需要参数之一的组参数(设置?) [英] Group parameter (set?) requiring one of the parameters

查看:153
本文介绍了需要参数之一的组参数(设置?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置需要三组参数之一的参数,并包括一个整数和一个冒号;

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

通过Microsoft Docs无法完全了解参数集,请在设置方面需要帮助.

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

最后,该参数将用于Robocopy的MinAge参数,如果使用-month:2,我将剔除2,乘以30.4167(月平均天数)并插入作为Robocopy参数.我有最后一部分,只是没有参数部分.

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.

推荐答案

我认为这可以解释一下.下面的函数使用三个参数,所有参数均具有不同的参数集名称.

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

在ISE编辑器中使用此选项将仅允许使用三个参数之一. 该函数还具有DefaultParameterSetName,这意味着如果您未指定参数名称,则将使用默认设置(在本例中为"ByDays"设置).

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).

像这样使用它:

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"

希望有帮助

这篇关于需要参数之一的组参数(设置?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆