Passing empty string '' to function sends '0'

Welcome Forums General PowerShell Q&A Passing empty string '' to function sends '0'

This topic contains 2 replies, has 2 voices, and was last updated by

11 months, 1 week ago.

  • Author
  • #96779

    Points: 45
    Rank: Member

    Spoke too soon. Im trying something else.


  • #96785

    Points: 1,811
    Helping HandTeam Member
    Rank: Community Hero

    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

    Points: 45
    Rank: Member

    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 {
            [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"
            } })]
        Write-Verbose -Message ("Number {0} was passed into function" -f $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!"
            $Suffix = $Number.ToString("000")
        Write-Verbose -Message ("Suffix to be used: {0}" -f $Suffix)
        return $Suffix

    Thanks, Don!

The topic ‘Passing empty string '' to function sends '0'’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort