#powershell Get-Date v.s. [datetime] Format and System Locale III

On a non-US system locale Windows machine[1], running this statement in a #powershell script will fail:

[datetime]$dt1 = (Get-Date).DateTime
Cannont convert value “Dienstag, 12. Dezember 2017 22:20:20” to type “System.DateTime”. Error: “The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.”
At line:1 char:1
+[datetime]$dt1 = (Get-Date).DateTime
+ CategoryInfo : MetadataError: (:) [], ArgumentTransformationMetadataException
+ FullyQualifiedErrorId : RuntimeException

To resolve this, … wrap the script around as illustrated:

$oCulture = Get-Culture
[System.Threading.Thread]::CurrentThread.CurrentCulture = New-Object “System.Globalization.CultureInfo” “en-us”
[System.Threading.Thread]::CurrentThread.CurrentCulture = $oCulture

[1] e.g.
CurrentCulture: de-CH
CurrentUICulture: en-US

Bookmark the permalink.

Leave a Reply