参数集的最佳实践设置

时间:2017-06-07 13:26:23

标签: powershell parameters

我试图设置参数集,但我不确定这是否是我尝试做的最佳做法。我正在寻找的设置如下:

$FolderSetup - Not Manditory.  [ValidateSet("Yes", "No"] Default is "No"
    If "Yes" is used, then no following parameters should be able to be selected
$OSVersion - Manditory.  [ValidateSet("2008SP2", "2008R2", "2012R2", "2016", "All")].  
    If "All" is used, then no following parameters should be able to be selected

$InputFile - Not Manditory - User inputs location of file
$OutputFolder - Not Manditory.  - User inputs desired output location
    $InputFile must be used before $OutputFolder can be used.

示例:

SinglePackage -FolderSetup 'Yes'
    #No Other Parameters can be used
SinglePackage -OSVersion 'All'
    #No Other Parameters can be used
SinglePackage -OSVersion '2008SP2'
SinglePackage -OSVersion '2008SP2' -InputFile 'C:\Temp\MyFile.txt'
SinglePackage -OSVersion '2008SP2' -InputFile 'C:\Temp\MyFile.txt' -OutputFolder 'C:\Temp\MyFolder'
SinglePackage -OSVersion '2008SP2' -OutputFolder 'C:\Temp\MyFolder'
    #Not Allowed.  Must have -InputFile if using -OutputFolder   

2 个答案:

答案 0 :(得分:0)

以下是你要求的params ...

Function TEST(){
    Param(
        [Parameter(Position=0, Mandatory=$true)]
        [switch]$FolderSetup,

        [Parameter(Position=1, Mandatory=$false)]
        [ValidateSet("2008SP2", "2008R2", "2012R2", "2016", "All")]
        [string]$OSVersion,

        [Parameter(ParameterSetName="InputFiles", Mandatory=$false)]
        [string]$InputFile,

        [Parameter(ParameterSetName="InputFiles", Mandatory=$false)]
        [string]$OutputFolder
    )

}

答案 1 :(得分:0)

我认为最好的方法是按如下方式声明参数块:

param(
    [Parameter(Mandatory=$true,ParameterSetName="Folder")]
    [switch]$FolderSetup,

    [Parameter(Mandatory=$true,ParameterSetName="AllVersions")]
    [Alias("AllOS")]
    [switch]$All,

    [Parameter(Mandatory=$true,ParameterSetName="OSSpecific")]
    [Parameter(Mandatory=$true,ParameterSetName="IOFolders")]
    [ValidateSet("2008SP2","2008R2", "2102R2", "2016")]
    [string]$OSVersion,

    [Parameter(Mandatory=$true,ParameterSetName="IOFolders")]
    [string]$InputFolder,

    [Parameter(ParameterSetName="IOFolders")]
    [string]$OutputFolder
)

这会强制将呼叫置于您上面提供的有效表单之一,并禁止无效组合。如果它无法确定正在使用哪组参数,则会抛出错误说明 - 但这可以保证尝试无效的参数组合。

它确实存在您无法使用-OSVersion "All"的约束;请改用-All-AllOS