【问题标题】:How to use a ValidateSet and still allow $null on an Array parameter?如何使用 ValidateSet 并且仍然允许在 Array 参数上使用 $null?
【发布时间】:2015-04-15 17:14:00
【问题描述】:

我有一个方法需要接受一个字符串数组作为参数,但该数组只能包含有效字符串。我的问题是,如果我确保[AllowNull()][AllowEmptyCollection()],该方法仍然失败

function SomethingSomethingAuthType {
    param(
        [parameter(Mandatory=$true,position=0)] 
        [ValidateSet('anonymousAuthentication','basicAuthentication','clientCertificateMappingAuthentication','digestAuthentication','iisClientCertificateMappingAuthentication','windowsAuthentication')] 
        [AllowNull()] 
        [AllowEmptyCollection()] 
        [array] $authTypes
    )

    $authTypes | % {
        Write-Host $_ -f Green
    }

}

SomethingSomethingAuthType $null

SomethingSomethingAuthType : 无法验证参数上的参数 'authTypes'。参数为 null、空或 参数集合包含一个空值。提供一个集合 不包含任何空值,然后再次尝试该命令。在 行:16 字符:32 + SomethingSomethingAuthType $null + ~~~~~ + CategoryInfo : InvalidData: (:) [SomethingSomethingAuthType], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationError,SomethingSomethingAuthType

我需要做什么才能让$null 被传入,同时还要验证集合以确保正确的类型?

【问题讨论】:

    标签: validation powershell


    【解决方案1】:

    这里的答案是使用[Enum[]] 而不是[array],并一起删除 ValidateSet。

    function SomethingSomethingAuthType {
        param(
            [parameter(Mandatory=$true,position=0)] 
            [AllowNull()] 
            [AllowEmptyCollection()] 
            [AuthType[]] $authTypes
        )
    
        Write-Host 'Made it past validation.'
    
        if(!$authTypes) { return }
    
        $authTypes | % {
            Write-Host "type: $_" -f Green
        }
    
    }
    
    # Check if the enum exists, if it doesn't, create it.
    if(!("AuthType" -as [Type])){
     Add-Type -TypeDefinition @'
        public enum AuthType{
            anonymousAuthentication,
            basicAuthentication,
            clientCertificateMappingAuthentication,
            digestAuthentication,
            iisClientCertificateMappingAuthentication,
            windowsAuthentication    
        }
    '@
    }
    
    # Testing
    # =================================
    
    SomethingSomethingAuthType $null                                          # will pass
    SomethingSomethingAuthType anonymousAuthentication, basicAuthentication   # will pass
    
    SomethingSomethingAuthType invalid                                        # will fail
    SomethingSomethingAuthType anonymousAuthentication, invalid, broken       # will fail
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-07
      • 1970-01-01
      • 2011-12-25
      • 1970-01-01
      • 2012-08-09
      • 2018-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多