为什么 $Null 验证在 powershell 函数中失败?

Why $Null validation failed in powershell function?

团队!

我有参数 $Data 的验证脚本。 获取 $null 时失败。

怎么了?

[CmdletBinding()]
    Param (
        [Parameter(  HelpMessage = "PsObject data." )]
        [AllowNull()]
        [AllowEmptyCollection()]
        [AllowEmptyString()]
        [ValidateScript({
            if ( ( $_ -eq $null ) -or ( $_ -eq '' ) ){
                $true
            }
            else {
                (( !( $_.GetType().IsValueType ) ) -and ( $_ -isnot [string] ))
            }
        })]        
        $Data,
...

$UserObject = Show-ColoredTable -Data $null -View 'SamAccountName', 'Name', 'DistinguishedName', 'Enabled'  -Title "AD User list" -SelectMessage "Select AD user(s) to disable VPN access: " -AddRowNumbers -AddNewLine -SelectField "SamAccountName"

大多数验证属性与 [AllowNull()] 不兼容,因为在调用自定义验证之前,它们首先检查的是输入对象是否 $null

将验证逻辑移到函数体内:

[CmdletBinding()]
Param (
    [Parameter(  HelpMessage = "PsObject data." )]
    [AllowNull()]
    [AllowEmptyCollection()]
    [AllowEmptyString()]
    $Data
)

# validate $Data here before the rest of the script/command