Passing empty string '' to function sends '0'

This topic contains 2 replies, has 2 voices, and was last updated by  Michael 2 months ago.

  • Author
    Posts
  • #96779

    Michael
    Participant

    Spoke too soon. Im trying something else.

    Thanks!

  • #96785

    Don Jones
    Keymaster

    PowerShell does love its coercion. So, know that your ValidatePattern isn't helping; that forces the input into a string in order to do a regex match. [int] along makes sure you get an integer, and you can use a ValidateRange if you need to limit to, say, 100 to 999. Aside from that, in PowerShell's mind, an empty string _is the same as zero_. I'm not sure there's a declarative way to change it's mind on that, unless I'm misunderstanding what you're after.

  • #96813

    Michael
    Participant

    I see. That makes sense. I just want to ensure that a terminating failure occurs if someone tries to pass an empty string " or " ", so after reading what you replied with I modified the function as such and all current functionality remained intact along with failing for passing in those empty values. 🙂

    I had to add the ValidateScript validation to catch passing in " ". The ValidateNotNullOrEmpty did not catch that but It did catch passing in " or "".

    
    function Add-Increment {
        [CmdletBinding()]
        param(
        
        [ValidateNotNullOrEmpty()]
            [ValidateScript({ if([string]::IsNullOrWhiteSpace($_))
            {
                throw "The argument is null or whitespace. Provide and argument that is not null or whitespace, and then try the command again"
            } })]
    
        $Number
    
        )
        
        Write-Verbose -Message ("Number {0} was passed into function" -f $Number)
    
        $Number++
    
        Write-Verbose -Message ("After increment, Number is: {0}" -f $Number)
    
        $CharCount = $(($Number | Measure-Object -Character).Characters)
    
        if($CharCount -gt 3)
        {
            throw "Number suffix $Number surpassed 3 digits!"
        }
        else 
        {
            $Suffix = $Number.ToString("000")
        }
    
        Write-Verbose -Message ("Suffix to be used: {0}" -f $Suffix)
        return $Suffix
    }
    

    Thanks, Don!

You must be logged in to reply to this topic.