11

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

 3 years ago
source link: https://thomasrayner.ca/quick-tip-allow-a-null-value-for-an-object-that-doesnt-normally-allow-it/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK