Setting a Nullable Enum to $null in PowerShell causes aSystem.Management.Automation.PSInvalidCastException
exception. This is unexpected (to me at least). Is there a reasonable explanation for this? Here is an example that shows how setting a Nullable Int32 is successful, but setting a Nullable Enum causes an exception:
Add-Type @"
public enum ColorEnum
{
Red = 1,
Blue = 2,
Green = 3,
}
public class Thing
{
public ColorEnum? NullableColor = ColorEnum.Blue;
public System.Int32? NullableInt = 123;
}
"@
$test = New-Object Thing
# Setting the Nullable Int32 to $null works, as expected.
$test.NullableInt = $null
# Setting the Nullable Enum to $null causes exception.
$test.NullableColor = $null
The exception message reads:
Exception setting "NullableColor": "Cannot convert null to type "ColorEnum" due to enumeration values that are not valid. Specify one of the following enumeration values and try again. The possible enumeration values are "Red, Blue, Green"."
The reason I would like to be able to use a Nullable Enum, rather than an Enum with a default value of 0, is because the Enum I want to use represents a nullable database column which is expected to be null when no valid value is set. I cannot change the database model, so unfortunately it feels like the solution may be to use an Int32 instead of an Enum.
Has anyone else experienced this? Is it a bug perhaps?
$PsVersionTable:
Name Value
---- -----
PSVersion 3.0
WSManStackVersion 3.0
SerializationVersion 1.1.0.1
CLRVersion 4.0.30319.18444
BuildVersion 6.2.9200.16481
PSCompatibleVersions {1.0, 2.0, 3.0}
PSRemotingProtocolVersion 2.2
This was a bug in PowerShell 4 (and probably 3, but I haven't tried it).
It has been fixed in PowerShell V5 (verified against recent internal builds), I believe it should be fixed in public builds like the September WMF5 preview or Windows 10 preview builds.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With