Suppressing Error output for Type Conversion on $Null

[Datetime]$Null will error with

InvalidArgument: Cannot convert null to type "System.DateTime".

How would you handle $Null values in this scenario to suppress these errors?

try {} catch {} ?

if (-not $Null) {[Datetime]} ?

Any other ways?

Based on the information given, I would go for

if ($myVar -ne $null) {
    $myVar -as [DateTime]
}

1 Like

Use “Sysem.Nullable” class:

[System.Nullable[datetime]] $null

To compare it against null, you should always do so by placing $null on left side,
not right side like suggested in comment above:

if ($null -ne $MyVariable) {
# do non null stuff...
}

In the case with date time, it can’t be assigned null, following is an error:

[System.Nullable[datetime]] $MyNullable = [datetime] $null

To get around this you do it like so:

[System.Nullable[datetime]] $MyNullable = [System.Nullable[datetime]] $null

Checking for null as usual:

if ($null -ne $MyNullable)
{
	# do non null stuff...
}
2 Likes

Thanks for picking me up on that. I didn’t know that putting it on the left is best practice and I wasn’t aware of the potential problems with having it on the right.

1 Like

matt-bloomfield
You’re welcome mate, I learned this one hard way :stuck_out_tongue:

1 Like

A great topic!

You can check the class type and its overloads by executing the new constructor without specifying parameters. Below is the shorthand for what @metablaster supplied with the new .ctor listed. This style of notation is handy in PowerShell classes.

[nullable[datetime]]::new

results

Demo: testing the type with values

The first two lines return True because they agree with the declared type (i.e., null and a date value). The last line raises an error because it attempts to set the variable with a string value.

cls
[nullable[datetime]]$dt = $null; $dt -eq $null; rv dt;
[nullable[datetime]]$dt = (Get-Date).Date; $dt.GetType().Name -eq "DateTime"; rv dt;
[nullable[datetime]]$dt = "Alice"; $dt;

Remarks

I put Remove-Variable at the end of the first two strings to prevent what I call “variable bleed”. Leave it off and the final line returns the error and the date value from the second line.

-d