Update: @PetSerAl's answer to the linked question provides excellent technical background, which I've since tried to summarize in this answer.
My understanding of how PowerShell expands (interpolates) scalar values (variable references or subexpressions that expand to a single object) in double-quoted strings is as follows:
.psobject.ToString()
is called on the resulting object, which allows PS to provide a custom stringified value, such as for[pscustomobject]
instances.If no custom stringification is applied, the underlying .NET type's
.ToString()
method is called (which in the absence of an overridden.ToString()
method results in just the full type name being returned).
For a complete overview of PS string interpolation, see this answer of mine.
However, there appears to be a third case:
[datetime]
instances implicitly string-expand in a way that is distinct from explicitly calling either .psobject.ToString()
or .ToString()
.
For instance, on a US English system, as of PSv5.1:
# IMPLICIT stringification: string expansion (interpolation)
PS> "$(Get-Date)"
02/13/2017 12:53:42
# EXPLICIT stringification with [.psobject].ToString()
PS> (Get-Date).psobject.ToString() # (Get-Date).ToString() yields the same
2/13/17 12:54:44 PM # !! DIFFERENT RESULT
Turns out that casting to [string]
behaves the same way as using string expansion (interpolation), so "$(Get-Date)"
and [string] (Get-Date)
yield the same.
- What is the underlying implicit stringification mechanism in this case?
- Why does it differ from explicit stringification?
- When and to what types is this mechanism applied?