My understanding of PowerShell's string embedding syntax "$($object)"
has always been that $object
is cast to [System.String]
, which invokes $object.ToString()
. However, I've noticed this curious behavior with the [DateTime]
class using PowerShell 4.0 on Windows 8.1.
PS> $x = Get-Date
PS> $x.GetType() | select -ExpandProperty Name
DateTime
PS> $x.ToString()
2015-05-29 13:36:06
PS> [String]$x
05/29/2015 13:36:06
PS> "$($x)"
05/29/2015 13:36:06
It seems that "$($object)"
gives the same behavior as casting to string, but is clearly producing a different result from $object.ToString()
. $x.ToString()
is consistent with the short date format set in intl.cpl (yyyy-MM-dd). [String]$x
appears to use the en-US default.
It is possible this is simply a bug in the DateTime class, but I'm more surprised that the different methods of converting an object to a string produce different results. What are the rules for casting an object to a string, if not calling ToString()
? Is the DateTime class simply a special case because of its overloading of ToString(String)
?