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?
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.
To make a parameter mandatory add a "Mandatory=$true" to the parameter description. To make a parameter optional just leave the "Mandatory" statement out.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With