Explain AllowEmptyString() and AllowEmptyCollection() in PowerShell Advanced Function.

PowerShellMicrosoft TechnologiesSoftware & Coding

AllowEmptyString() attribute works with the string variable and AllowEmptyCollection() work with the array of different data types (Collection).

Consider the example below. Here, we are using a mandatory variable $name which is a string and $stringarray which is a string array.

function print_String{
   [cmdletbinding()]
   param(
      [parameter(Mandatory=$True)]
      [string]$name,
   )
   Write-Output "Writing a single string"
   $name
}

If we get the output of the above variable it will generate an error below.

PS C:\WINDOWS\system32> print_String
cmdlet print_String at command pipeline position 1
Supply values for the following parameters:
name:
print_String : Cannot bind argument to parameter 'name' because it is an empty
string.
At line:1 char:1
+ print_String
+ ~~~~~~~~~~~~
   + CategoryInfo             : InvalidData: (:) [print_String], ParameterBindin
g
   ValidationException
      + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAl
l
   owed,print_String

As you can see in the above output, the script doesn’t accept the empty string. To allow the empty string, you need to use the AllowEmptyString() argument, so the error won’t be generated.

function print_String{
   [cmdletbinding()]
   param(
      [parameter(Mandatory=$True)]
      [AllowEmptyString()]
      [string]$name
   )
   Write-Output "Writing a single string"
   $name
}

Output 

PS C:\WINDOWS\system32> print_String
cmdlet print_String at command pipeline position 1
Supply values for the following parameters:
name:
Writing a single string

In the above example, you can see that once you add the argument AllowEmptyString(), the program accepts the Empty string. Similarly, when you add the AllowEmptyCollection() argument, PowerShell will accept the empty values of an array.

function print_String{
   [cmdletbinding()]
   param(
      [parameter(Mandatory=$True)]
      [AllowEmptyCollection()]
      [string[]]$stringarray
   )
   Write-Output "Writing a string array"
   $stringarray
}

Output

PS C:\WINDOWS\system32> print_String
cmdlet print_String at command pipeline position 1
Supply values for the following parameters:
stringarray[0]:
Writing a string array
raja
Published on 04-May-2020 10:33:32
Advertisements