Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing null to a mandatory parameter to a function

Tags:

Effectively my problem comes down to this:

I can't have a function with a mandatory parameter and pass $null to that parameter:

Function Foo {     Param     (         [Parameter(Mandatory = $true)][string] $Bar     )      Write-Host $Bar }  Foo -Bar $null 

This returns foo : Cannot bind argument to parameter 'Bar' because it is an empty string.

Likewise, making it an array also fails:

Function Foo {     Param     (         [Parameter(Mandatory = $true)][string[]] $Bar     )      Write-Host $Bar }  Foo -Bar 1, 2   > 1 2  Foo -Bar 1, 2, $null  > foo : Cannot bind argument to parameter 'Bar' because it is an empty string. 

In programming terms it is entirely possible to have a function that accepts a mandatory nullable parameter, but I can't find a way of doing that in PowerShell.

How do I do it?

like image 321
cogumel0 Avatar asked Aug 23 '14 08:08

cogumel0


People also ask

Can you pass null into a function?

NULL is a valid pointer: it points to memory location zero. Therefore you can pass NULL into a function that takes a Book* pointer, because it IS a Book* pointer.

How do you make a parameter Mandatory?

To make a parameter mandatory add a "Mandatory=$true" to the parameter description. To make a parameter optional just leave the "Mandatory" statement out.

Can null be a parameter?

Short answer is YES, you can use null as parameter of your function as it's one of JS primitive values. Documentation: You can see it in the JavaScript null Reference: The value null represents the intentional absence of any object value.


1 Answers

You should be able to use the [AllowEmptyString()] parameter attribute for [string] parameters and/or the [AllowNull()] parameter attribute for other types. I've added the [AllowEmptyString()] attribute to the function from your example:

Function Foo {     Param     (         [Parameter(Mandatory = $true)]         [AllowEmptyString()]  <#-- Add this #>         [string] $Bar     )      Write-Host $Bar }  Foo -Bar $null 

For more info, check out the about_Functions_Advanced_Parameters help topic.

Be aware that PowerShell will coerce a $null value into an instance of some types during parameter binding for mandatory parameters, e.g., [string] $null becomes an empty string and [int] $null becomes 0. To get around that you have a few options:

  • Remove the parameter type constraint. You can check for $null in your code and then cast into the type you want.
  • Use System.Nullable (see the other answer for this). This will only work for value types.
  • Rethink the function design so that you don't have mandatory parameters that should allow null.
like image 77
Rohn Edwards Avatar answered Sep 19 '22 22:09

Rohn Edwards