How to pass Null to a Boolean Parameter in Powershell
Today, I had an interesting discovery in a PowerShell DSC project. The issue that I faced centered on an optional parameter that I had cast as Boolean. I want to make sure that the only valid options are $True or $False as these are the only valid values. Everything worked perfectly until I realized that there was actually another possible option…. Nothing. Before we can understand the issue, we need to investigate the behavior.
Function Test-LightSwitch { param( [boolean] $TestCase ) Write-Host $( "The test case is " + $TestCase ) }
When I run this function in my lab, I will see some very expect results. If I pass the parameter with $True or $False it returns exactly what I would want to see and prints the $TestCase variable. What happens if I don’t pass the parameter? The PowerShell function will return $False. Remember a boolean type is a light switch and can only be on or off.
How do we check to see if this optional parameter is was actually sent so that we can set the value to $True or $False. I found that there was an option in PowerShell to [AllowNull()]
that could be added to my parameter. It didn’t work and just gave me the same results. After a bit of searching, I found an interesting article on a .NET class called Nullable(T) Structure. It was here that I realized that I might have found a way to TypeCast a boolean and support Nullable. It took a little trial and error but I figured out that I had to cast [Nullable]
and then put the [boolean]
inside. Essentially, I cast this as a Nullable Boolean.
EUREKA! This was exactly what I wanted for my DSC property. I could now handle $True, $False, and $NULL. Heck I could even skip the parameter all together. Take a look at the revised example.
Function Test-LightSwitch { param( [Nullable[boolean]] $TestCase ) if(-not [string]::IsNullOrEmpty($TestCase) ){ Write-Host $( "The test case is " + $TestCase ) } else { Write-Host "Hey buddy, I don't read minds!" } }