Strongly Typed Variables

by Nov 10, 2008

Unless you override how PowerShell stores variable content, you may find that PowerShell does not automatically pick the best type. For example, when you assign a date to a variable, the date is stored as string:

PS> $date = 'November 12, 2008'
PS> $date.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
PS> $date.AddDays(10)
Method invocation failed because [System.String] doesn't contain a method named 'AddDays'.
At line:1 char:14
+ $date.AddDays <<<< (10)

You do not get the special date and time functions provided by the DateTime type like for example AddDays. In this case, it is better to manually assign the appropriate type:

PS> $date = [DateTime]'November 12, 2008'
PS> $date.GetType()
PS> $date.AddDays(10)
Saturday, November 22, 2008 12:00:00 AM

In this last example, you converted the data to a specific type but your variable, $date, is still not strongly typed. You could still store data in it that is not a Date:

PS> $date = 'a new value'
PS> $date.GetType()

When you strongly type a variable, it no longer is versatile. Instead, it now only accepts data that can be converted into the type assigned to it:

PS> [DateTime]$date = 'November 12, 2008'
PS> $date.AddDays(-6)
PS> $date = 'this won't work because it is no date'
Unexpected token 't' in expression or statement.
At line:1 char:20
+ $date = 'this won't <<<< work because it is no date'