Quick Tip - Allow A Null Value For An Object That Doesn't Normally Allow It

In the PowerShell Slack channel (powershell.slack.com) a question came up along the lines of “I have a script that needs to pass a datetime object, but sometimes I’d like that datetime object to be null”. Never mind that maybe the script could be re-architected. Let’s solve this problem.

The issue is, if you try to assign a null value to a datetime object, you get an error.

[datetime]$null
Cannot convert null to type "System.DateTime".

The solution is super easy. Just make the thing nullable.

[nullable[datetime]]$null

This will return no output. So when you’re declaring the variable that will hold your datetime object, just make sure you make it nullable.

[nullable[datetime]]$date = $MaybeNullMaybeNot

Just for more proof this works as advertised, try this.

try { [datetime]$null; write-output 'worked!' } catch { write-output 'no worked!' }
no worked!

try { [nullable[datetime]]$null; write-output 'worked!' } catch { write-output 'no worked!' }
worked!

Cool!

Written on September 14, 2016