How to use ValidateSet and still allow $ null for Array parameter?

I have a method that should take an array of strings as a parameter, but this array can only contain valid strings. My problem is that if I guarantee [AllowNull()]as well [AllowEmptyCollection()], the method still doesn't work

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, empty . , , . : 16 char: 32 + SomethingSomethingAuthType $null + ~~~~~     + CategoryInfo: InvalidData: (:) [SomethingSomethingAuthType], ParameterBindingValidationException     + FullyQualifiedErrorId: ParameterArgumentValidationError, SomethingSomethingAuthType

, $null, , ?

+4
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
+5

All Articles