Home > Enterprise >  Why $Null validation failed in powershell function?
Why $Null validation failed in powershell function?

Time:11-04

team!

I have validation script for parameter $Data. It fail when it get $null.

whats wrong?

[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"

CodePudding user response:

Most validation attributes are incompatible with [AllowNull()] because the first thing they all check - before your custom validation is invoked - is whether the input object is $null or not.

Move the validation logic inside the function body:

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

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