Function fall down if it have got the array with empty string

Welcome Forums General PowerShell Q&A Function fall down if it have got the array with empty string

Viewing 1 reply thread
  • Author
    • #196703
      Topics: 9
      Replies: 8
      Points: 102
      Rank: Participant

      Strange thing.

      I have the next function:

      function TestFunc {
          param ([Parameter(Mandatory)][string[]] $array)
          Write-Host $array

      So, if I try to execute the next code:

      $arr = @("test1", "", "test2")
      TestFunc $arr

      I've got the error:
      Cannot bind argument to parameter 'array' because it is an empty string

      But if, I specify the AllowEmptyString() like this:

      function TestFunc {
          param ([Parameter(Mandatory)] [AllowEmptyString()] [string[]] $array)
          Write-Host $array

      all works fine.

      So, I tried to send the whole array to function, why does only one empty array element cause the error above ?

      Could somebody explain this behavior

    • #196724
      Topics: 10
      Replies: 1381
      Points: 1,509
      Helping Hand
      Rank: Community Hero

      The validation is occurring on the parameter, not within the function. The validation is ensuring that there is no empty values in the array and if you wish to override the default behavior you can provide the [AllowEmptyString()]. The parameter is being validated because internally the intention is to do a for loop to process each item, such as a computername which would break because it's null. If you do allow empty strings, you still have to handle the null value in your code. Parameter validation is basically trying to prevent issues later, so it is validating it's ready to be processed by the function.

Viewing 1 reply thread
  • You must be logged in to reply to this topic.