DateTime参数解析有不同locale

DateTime parameter parsing has different locale

我对 PowerShell 在涉及参数时如何处理表示 DateTime 的字符串感到有点困惑。我的脚本有一个参数定义如下:

[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
)

我想输入以下日期:1. 2016 年 4 月作为我的语言环境字符串 01.04.2016。现在 PowerShell 做了一些意想不到的事情(至少对我来说是这样):

  1. 当 PowerShell 查询缺少的必需参数时,我在命令提示符下输入字符串 01.04.2016。然后它被解析为 1. April 2016.
  2. 我直接在命令行中输入相同的字符串 01.04.2016 ZippenUndMailen.ps1 -von '01.04.2016',现在 PowerShell 使用 US notation 解析字符串作为 2016 年 1 月 4 日。

我有两个问题:

  1. 为什么 PowerShell 以不同的方式解析字符串?
  2. 如何最好地补救该行为?脚本应该被手动和通过 TaskScheduler 重复使用和调用,这种行为相当违反直觉。

Adwaenyth,我无法复制您看到的不同时间分辨率,但这很可能是文化问题...请参阅有关在 Powershell 中使用文化的问题 How to set culture in PowerShell?

我也无法复制它,尽管我当前的文化与 en-us 不同。 尝试从您的参数定义中删除 [DateTime] cast(将其设置为 [Parameter(Mandatory=$true, ParameterSetName='Kunde')]$von)并在您的代码中使用 $von = [DateTime]::Parse($von, (Get-Culture)) 以强制 PS 使用您当前的文化。

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.