问题
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