sql_dummy
sql_dummy

Reputation: 745

How to declare a datetime variable with null value

How I create a datetime, int variables with initializing then to null, I try this but it shows error

[datetime] $var1 = $null

Error:

WARNING: Error: Cannot convert value "var1" to type "System.DateTime". Error: "The string was not recognized as a valid DateTime. There is an unknown word starting at index 0."

Upvotes: 2

Views: 4072

Answers (1)

mklement0
mklement0

Reputation: 439777

[datetime] (System.DateTime) is a .NET value type, so you cannot set a variable of that type to $null - you can only set it to 0 in this case:

[datetime] $var1 = 0

If you do need the variable to contain $null, you have two options:

  • Do not type-constrain it (no type literal ([...]) to the left of the variable name):
$var1 = $null
  • Type-constrain it as a nullable value type:
[Nullable[datetime]] $var1 = $null

Upvotes: 7

Related Questions