validation - 如何使用 ValidateSet 并仍然允许在数组参数上使用 $null?

标签 validation powershell

我有一个方法需要接受字符串数组作为参数,但该数组只能包含有效字符串。我的问题是,如果我确保 [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 : Cannot validate argument on parameter 'authTypes'. The argument is null, empty, or an element of the argument collection contains a null value. Supply a collection that does not contain any null values and then try the command again. At line:16 char:32 + SomethingSomethingAuthType $null + ~~~~~ + CategoryInfo : InvalidData: (:) [SomethingSomethingAuthType], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationError,SomethingSomethingAuthType



我需要做什么才能允许 $null要传入,还要验证集合以确保适当的类型?

最佳答案

这里的答案是使用 [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

关于validation - 如何使用 ValidateSet 并仍然允许在数组参数上使用 $null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29656593/

相关文章:

date - SQL 不接受 PowerShell 日期格式

python - 什么是用于在 Python 中验证文件的好音频库?

scripting - 列出IIS6服务器场中所有已停止的应用程序池

powershell - 更新 Azure VM 规模集上的 VHD

javascript - 在发送表单之前,我如何制作一个基于 javascript 的表单复选框并使用 javascript 进行验证

powershell - Powershell防止重复的对象键

Powershell脚本为多个服务器远程获取网站的证书到期

javascript - symfony 中的 Jquery 验证和本地化

使用枚举列进行 Laravel 验证

java - 1-10 之间的正整数的阶乘。问题: Works only if valid input is greater than previous input