Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate PowerShell Function Parameters allowing empty strings?

Please try this:

function f1 {     param(     [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)]     [string]     $Text     )     $text }  function f2 {     param(     [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)]     #[string]     $Text     )     $text }  function f3 {     param(     [Parameter(Mandatory=$False,ValueFromPipelineByPropertyName=$true)]     [string]     $Text     )     $text }  f1 '' f2 '' f3 '' 

Here f1 throws an error. Now try

f2 $null  f3 $null     

This time only f2 throws an error. What I want is a function f, so that

f '' # is accepted f $null # returns an error 
like image 985
bernd_k Avatar asked Jun 19 '11 15:06

bernd_k


People also ask

How do you pass parameters to a function in PowerShell?

You can pass the parameters in the PowerShell function and to catch those parameters, you need to use the arguments. Generally, when you use variables outside the function, you really don't need to pass the argument because the variable is itself a Public and can be accessible inside the function.

How do I validate a path in PowerShell?

To validate the file or folder path inside the PowerShell function parameter, we need to use the ValidateScript command.

How do you make parameters mandatory in PowerShell?

To make a parameter mandatory add a "Mandatory=$true" to the parameter description. To make a parameter optional just leave the "Mandatory" statement out. Make sure the "param" statement is the first one (except for comments and blank lines) in either the script or the function.


1 Answers

The Mandatory attribute blocks null and empty values and prompts you for a value. To allow empty values (including null) add the AllowEmptyString parameter attribute:

function f1 {     param(     [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)]     [AllowEmptyString()]     [string]$Text     )     $text } 
like image 83
Shay Levy Avatar answered Oct 20 '22 23:10

Shay Levy