Setting the Nullable Enum to $ null. Should this raise a PSInvalidCastException?

Setting the Nullable Enum to $ null in PowerShell raises a System.Management.Automation.PSInvalidCastException exception. This is unexpected (at least for me). Is there any reasonable explanation for this? Here is an example showing how the installation of Nullable Int32 succeeded, but the installation of Nullable Enum throws 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 

Exception Message:

NullableColor exception parameter: "Cannot convert null to type" ColorEnum "due to invalid enum values. The following enum values โ€‹โ€‹and try again. Possible enum values:" Red, Blue, Green ".

The reason I would like to use a Nullable Enum rather than Enum with a default value of 0 is because the Enum that I want to use is a column with a null column, which is expected to be null when not Valid value is set. I canโ€™t change the database model, so unfortunately it looks like the solution might be to use Int32 instead of Enum.

Has anyone else experienced this? Perhaps this is a mistake?

$ 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 
+7
enums powershell nullable
source share
1 answer

This was a bug in PowerShell 4 (and probably 3, but I have not tried it).

It was fixed in PowerShell V5 (tested for recent internal builds), I believe that it should be fixed in public assemblies, such as the September preliminary versions of WMF5 or preliminary builds of Windows 10.

+5
source share

All Articles