
This is a very quick document to describe how to do a null coalesce in PowerShell that will also treat an empty string as a null value.
We use a combination of the shorthand null coalesce ?? with the ternary operator <condition> ? <true action> : <false action>
In the following sample $inputString is a variable that may contain a non-zero length text string, a zero length text string or null.
(!$inputString ? $null : $inputString) ?? "replacement text"
That’s it. One very short line of code. Here’s how it works:
Firstly within the brackets we have the ternary operator.
If !$inputString is True then $null else $inputString. The exclamation mark in front of the string variable is a shortcut to the -not operator. This causes it to treat the variable as boolean where null or empty is False and having a non-zero length value is True.
The -not operator reverses this so it returns True if it’s null or empty and False if it has a non-zero length value. Therefore we’re saying if the $inputString variable is null or empty, then output $null otherwise output the value of the string variable.
Next we use the null coalescing operator to simply coalesce the null with the replacement text.
In summary, the code in the brackets will convert an empty string to null otherwise it’ll just output the input as-is, then outside the brackets a null is replaced with “replacement text” otherwise output as-is. The net result, a null or empty string coalesce on one line with no cumbersome if statements or the IsNullOrEmpty() string method.
Here’s what ChatGPT came up with. It took a bit of back and forth to get there, it’s using the string method IsNullOrEmpty and puts the replacement text in the ternary operator instead of null, which is equally as valid. I’ll take the win based on the slightly shorter solution
