根据powershell

时间:2016-02-01 19:19:40

标签: powershell powershell-v2.0 powershell-v3.0 powershell-ise

我正在PowerShell 3.0中编写一个函数。应根据另一个参数的值将函数中的一个参数设置为强制参数。

函数声明如下:

function removeVolumeandArrayFromHost(){
Param( [Parameter(mandatory = $true)] [ValidateSet('iSCSI','FC')] $arrayType, ##IpAddress/Name of the target host 
   [Parameter(mandatory = $true)] $volumeName, ##Name of the volume to be disconnected. (Volume name as in the array.)
   [Parameter(mandatory = $false)] $FCACL, ##Access control list name to which volume is added (Related to FC Array only)

   ## Work with the parameters given.
}

在上面的函数中,参数'$ arrayType'的值可以是'iSCSI'或'FC'。

仅当$ arrayTpe ='FC'时,参数$ FCACL才是强制性的(强制= $ true)。如果$ arrayType ='iSCSI',那么$ FCACL参数不应该是强制性的(强制= $ false)

我尝试使用参数名称但它有点帮助,因为我需要查看参数$ arrayType的值来决定$ FCACL是否是强制性的。

任何类型的帮助或指针都将受到高度赞赏。

提前多多感谢。 :)

3 个答案:

答案 0 :(得分:2)

您可以使用动态参数,或者如果将$arrayType变量更改为开关,则可以使用ParameterSetName强制执行。事情变成这样:

Function removeVolumeandArrayFromHost(){
Param( 
    [Parameter(ParameterSetName="FC")][switch]$FC,
    [Parameter(ParameterSetName="iSCSI")][switch]$iSCSI,
    [Parameter(ParameterSetName="FC",Mandatory=$true)] [string]$FCACL,

    [Parameter(mandatory = $true)] [string]$volumeName
)
....
   ## Work with the parameters given.
}

或者,如果您知道您只处理FC或iSCSI,那么您只需要一个switch语句来说明它是否为FC。如果存在-FC开关,则它将调用ParameterSetName=FC并需要-FCACL参数。如果您排除-FC开关,则认为它是iSCSI,ParameterSetName将确保您不需要-FCACL

Function removeVolumeandArrayFromHost(){
Param( 
    [Parameter(ParameterSetName="FC")][switch]$FC,
    [Parameter(ParameterSetName="FC",Mandatory=$true)] [string]$FCACL,

    [Parameter(mandatory = $true)] [string]$volumeName
)
....
   ## Work with the parameters given.
}

答案 1 :(得分:0)

一个选项是使用函数的Begin / Process / End部分并在" Begin"中处理这类内容。部分,而不是像其他答案所建议的那样添加动态参数。

答案 2 :(得分:0)

Chris N给出的建议完全适用于我的情况,因为我不得不以这种方式处理一个参数。我的理解是,如果处理许多这样的参数,动态参数将是更好的选择。

我在这里添加代码更加清晰。

function removeVolumeandArrayFromHost(){
    Param( [Parameter(mandatory = $true)] [ValidateSet('iSCSI','FC')] $arrayType, ##IpAddress/Name of the target host 
       [Parameter(mandatory = $true)] $volumeName, ##Name of the volume to be disconnected. (Volume name as in the array.)
       [Parameter(mandatory = $false)] $FCACL) ##Access control list name to which volume is added (Related to FC Array only)       
    begin{
        if (($arrayType -eq 'FC') -and ($FCACL -eq $null)){
            Write-Error "For a FC Array, the FCACL parameter cannot be null."
            return
        }
    }
    process{
        .....
        .....
    }
}

谢谢大家的意见和建议。我感谢您的帮助。

相关问题