Search code examples
parsingpowershelldatetimelocale

DateTime parameter parsing has different locale


I'm a little puzzled by how PowerShell treats a string that represents a DateTime when it comes down to parameters. My Script has a parameter definition as follows:

[CmdletBinding(DefaultParameterSetName='Kunde')]
param(
    [Parameter(Mandatory=$true, ParameterSetName='Kunde')]
    [string]$KdNr,
    [Parameter(Mandatory=$true, ParameterSetName='Kunde')]
    [DateTime]$von,
    [Parameter(Mandatory=$true, ParameterSetName='Kunde')]
    [DateTime]$bis,
    [Parameter(Mandatory=$true, ParameterSetName='Kunde')]
    [string]$Empfaenger
)

I want to enter the following date: 1. April 2016 as my locale string 01.04.2016. Now PowerShell does something that is unexpected (at least to me):

  1. I enter the string 01.04.2016 at the command prompt when PowerShell queries the missing mandatory parameter. Then it gets parsed to 1. April 2016.
  2. I enter the same string 01.04.2016 directly at the commandline like this ZippenUndMailen.ps1 -von '01.04.2016' and now PowerShell parses the string using the US notation as January 4th 2016.

I've got two questions:

  1. Why does PowerShell parse the strings differently?
  2. How do I best remedy that behaviour? The Script should be reused and called both manually and via TaskScheduler and this behaviour is rather counter intuitive.

Solution

  • I can't reproduce it too, despite my current culture being different from en-us. Try removing [DateTime] cast from your parameter definition (set it to [Parameter(Mandatory=$true, ParameterSetName='Kunde')]$von) and use $von = [DateTime]::Parse($von, (Get-Culture)) in your code to force PS to use your current culture.

    More info:

    To prevent subtle internationalization issues from popping into your scripts, PowerShell treats [DateTime] '11/26/2007' (a date constant) like a language feature – just as it does [Double] 10.5 (a numeric constant.) Not all cultures use the decimal point as the fractions separator, but programming languages standardize on it. Not all cultures use the en-US DateTime format, resulting in millions of internationalization bugs when people don’t consider the impact of having their software run in those cultures.