0

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.
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Adwaenyth
  • 2,020
  • 12
  • 24

2 Answers2

3

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.

Community
  • 1
  • 1
beatcracker
  • 6,714
  • 1
  • 18
  • 41
  • That kinda solved it. Just had to remove the explicit `[string]` definition in the param definition. Otherwise PS would just convert the parsed `DateTime` back to a `string`. Without the explicit data type it works fine and is converted to a `DateTime`. – Adwaenyth Apr 14 '16 at 09:09
0

Adwaenyth, I can't replicate the differing time resolution you are seeing but it is most likely a culture issue... see this question regarding using culture in Powershell How to set culture in PowerShell?

Community
  • 1
  • 1
Djarid
  • 446
  • 4
  • 11