kafka kafka - 10 months ago 51
PowerShell Question

Why in PowerShell does embedding a DateTime object in a string lose the DateTime locale?

The locale of my machine is UK (en-gb). When I do the following (to check expiration date of an SSL cert) the DateTime object stores the value in UK format

$expiration = Get-Date $req.ServicePoint.Certificate.GetExpirationDateString()

See here what happens firstly if you just have the value printed to the command prompt, and secondly what happens if you try to embed that DateTime object value within a string.

19 December 2016 23:59:59
PS>write-host "this is the expiration: $expiration"
this is the expiration: 12/19/2016 23:59:59

So we see that it has switched to non UK format (should be 19/12/2016). Why is this, and is there a simple workaround?


It's a string expansion problem and a bit of a pain I'm afraid. You know this one to display incorrectly:

"$(Get-Date 01/02/2016)"

These however, display as you'd expect:

(Get-Date 01/02/2016).ToString()
"$((Get-Date 01/02/2016).ToString())"

Both of these approaches work to work around the problem:

$expiration = Get-Date 01/02/2016
write-host "this is the expiration: $($expiration.ToString())"
write-host ("this is the expiration: {0}" -f $expiration)

You see similar ignorance of the time zone when casting to DateTime:

[DateTime]$var = "01/02/2016"