Two Type Casts (and one bug)

by May 29, 2023

To explicitly convert one data type to another, PowerShell offers two ways:

 
PS> [int]5.6
6

PS> 5.6 -as [int]
6  
 

While both approaches yield identical results in most cases, there are subtle differences:

  • When you add the target type *before* the data, PowerShell uses the US culture and emits an exception when conversion fails.
  • When you use the “-as” operator, PowerShell uses your local culture and emits no exception when conversion fails.

The different cultures become important when you convert i.e. string to datetime on a non-English system:

 
PS> [datetime]'1.5.23'

Donnerstag, 5. Januar 2023 00:00:00



PS> '1.5.23' -as [datetime]

Montag, 1. Mai 2023 00:00:00  
 

Finally, both approaches feature a strange bug where type conversion works even though the input string is obviously garbled:

 
PS> [Type] 'int]whatever'

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Int32                                    System.ValueType


PS> 'int]whatever' -as [Type]

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Int32                                    System.ValueType   
 

Don’t take advantage of this bug though as it will be fixed soon in PowerShell 7.


Tweet this Tip! Tweet this Tip!