Skip to content

Date parameters handled differently for compiled c# cmdlets and functions.  #16767

Closed

Description

Prerequisites

Steps to reproduce

If a cmdlet takes a parameter of type System.DateTime a parameter passed to it is parsed using the local date format.
If a function takes a parameter of type System.DateTime a parameter passed to it is parsed using the Invariant time format.

Note this will not be visible if the culture is US.
For example

ps > set-culture fr-Fr
ps > pwsh -nologo
ps > get-date
mardi 18 janvier 2022 17:57:15

ps > New-TimeSpan -Start "18 janvier 2022" -end "19 janvier 2022" | % days   # French months recognized
1
ps > function test {[cmdletbinding()] param ([system.datetime]$start, [system.datetime]$End) $end.Subtract($start)}
ps > test -Start "18 janvier 2022" -end "19 janvier 2022"
test: Cannot process argument transformation on parameter 'start'. Cannot convert value "18 janvier 2022" to type "System.DateTime". Error: "The string '18 janvier 2022' was not recognized as a valid DateTime. There is an unknown word starting at index '3'."

ps > New-TimeSpan -Start 3/1/2022 -end 1/3/2022 | % days    # parsed as d/m/y 
57
> test  -Start 3/1/2022 -end 1/3/2022 | % days                   # parsed as m/d/y
-57

I compiled the cmdlet below and it behaved as the built in cmdlet did.

using System;
using System.Management.Automation;

namespace psmodule {
    [Cmdlet(VerbsDiagnostic.Test,"SampleCmdlet")]
    public class TestSampleCmdletCommand : PSCmdlet {
        [Parameter(Position = 0)]
        public DateTime Before { get; set; }
        [Parameter(Position = 1)]
        public DateTime After { get; set; }
        protected override void BeginProcessing()  {}
        protected override void ProcessRecord()    { WriteObject(After.Subtract(Before) ); }
        protected override void EndProcessing()    {}
    }
}

fixing this would be a breaking change I would like to understand if there is a reason for it.

Expected behavior

Consistent. See actual behavior

Actual behavior

ps > New-TimeSpan -Start 3/1/2022 -end 1/3/2022 | % days    # parsed as d/m/y 
57
> test  -Start 3/1/2022 -end 1/3/2022 | % days               # parsed as m/d/y
-57
ps > Test-SampleCmdlet -Before  "18 janvier 2022" -after "19 janvier 2022" | % days  # parsed in French 
1
ps >  test -Start "18 janvier 2022" -end "19 janvier 2022"  # Can only parse English 
<<error janvier isn't recognized>>

Error details

No response

Environment data

Name                           Value�[0m
----                           -----�[0m
PSVersion                      7.2.1
PSEdition                      Core
GitCommitId                    7.2.1
OS                             Microsoft Windows 10.0.19043
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

(same on 5.1.19041.1320)

Visuals

No response

Activity

  1. added
    Needs-Triage
    on Jan 18, 2022
  2. added
    Issue-Question
    on Jan 18, 2022
  3. iSazonov commented on Jan 18, 2022

    @iSazonov
    Collaborator

    To make script text culture-insensetive there is used Invariant culture for constants.
    C# code follow C# rules.

  4. MartinGC94 commented on Jan 18, 2022

    @MartinGC94
    Contributor

    Ooof that's a bad inconsistency to discover after so many years/versions.

    For full completion, the rules for casting to datetime are the same as functions use (uses the US format) while [datetime]::Parse uses the local format by default.

    Personally I'm in favor of making the breaking change so it follows the general .NET rules because I don't think people should have to check if a command is a cmdlet or function (and imagine replacing a cmdlet with a proxy function and discovering this the hard way).

  5. iSazonov commented on Jan 19, 2022

    @iSazonov
    Collaborator

    MartinGC94 The issue question is about script vs C#, not cmdlet vs function.

  6. jhoneill commented on Jan 19, 2022

    @jhoneill
    Author

    Ooof that's a bad inconsistency to discover after so many years/versions.

    For full completion, the rules for casting to datetime are the same as functions use (uses the US format) while [datetime]::Parse uses the local format by default.

    Actually, there is a different rule, and I found this by chance writing a blog post about it
    Casting with [type]$x syntax uses invariant culture. You can see it with US culture.

     > [datetime]::now.tostring()
    1/19/2022 9:08:40 AM
    
    > [string][datetime]::now
    01/19/2022 09:09:05
    

    US format for the clock is 12 hour with "AM/PM" Invariant is 24 clock.

    In French

    > [string][datetime]::now
    01/19/2022 09:10:37
    > [datetime]::now.tostring()
    19/01/2022 09:10:42
    > [datetime]::now.tostring("D")
    mercredi 19 janvier 2022
    
    > (1234567).tostring("N2")
    1 234 567,00
    

    So [string] was invariant, toString() uses local culture. In French the thousand separator is a space and comma is the decimal point but ...

    [double]"123,567"
    123567
    
    > [double]"1 234 567,00"
    InvalidArgument: Cannot convert value "1 234 567,00" to type "System.Double"
    

    casting with [double] uses invariant so comma is the thousand separator and space isn't allowed.

    If I want to use something that I know is local format I can use parse (or the [convert] class) without identifying the culture:

    > [double]::parse("1 234 567,00")
    1234567
    
    >([double]::parse("1 234 567,00")).tostring("E7")
    1,2345670E+006
    
    [string][datetime]::parse("mercredi 19 janvier 2022")
    01/19/2022 00:00:00
    

    The last one understands French (and only French) weekday and month names, -"January" would throw an error - and then [string] makes it invariant format (i.e. US Date and 24 hour clock). I can also call parse with a culture to say "This file was written with UK English, this one with US English, this one Canadian French, that one French French"

    So what do you think casting with -As does ?

    > ("mercredi 19 janvier 2022" -as [datetime] ).tostring('d')
    19/01/2022
    
     $null -eq ("1 234 567,00" -as [double])
    True
    

    -As returns null on a failed conversion and uses local for dates and invariant for numbers.

    MartinGC94 The issue question is about script vs C#, not cmdlet vs function.

    Ilya (@iSazonov) A trace shows that the parameter conversion is different depending on whether what is called is a a cmdlet written in C# and loaded from a .DLL or an "advanced function" / "script cmdlet" . loaded from a PS1 file.

    The result is if a module has commands that take date parameters, users need to know how those commands were implemented it. An author should be able to change that implementation detail without impacting the user, but as MartinGC94 already said a proxy function for Get-Date would break existing scripts.

    If the first thing a user meets is a function that takes dates they expect Get-Date to require invariant format. If the first thing they meet is Get-Date the expect local format to work anywhere.

  7. iSazonov commented on Jan 19, 2022

    @iSazonov
    Collaborator

    Dup #6989 and #3348 with PowerShell Committee conclusion Won't fix.

  8. iSazonov commented on Jan 19, 2022

    @iSazonov
    Collaborator

    You could investigate how many modules/cmdlets will break and share the info in #3348 if you vote for breaking change.

  9. jhoneill commented on Jan 19, 2022

    @jhoneill
    Author

    Ilya (@iSazonov) You either have an incredible memory or are much better with the search tools than I am :-)
    Thanks for sharing that one, I might not agree but at least I understand.

  10. iSazonov commented on Jan 19, 2022

    @iSazonov
    Collaborator

    You either have an incredible memory

    Ah, I'd want :-)
    The questions in this repository are too different for me to remember them all.
    Hopefully WGs will do it better since they will focus on a narrower range of issues.

    I might not agree but at least I understand.

    Me too. You can continue investigations in #3348

  11. jhoneill commented on Jan 19, 2022

    @jhoneill
    Author

    You could investigate how many modules/cmdlets will break and share the info in #3348 if you vote for breaking change.

    Making it consistent would change mean every parametrized script, and every function with a datetime parameter (inside a module or not) would change its behaviour. And so anything that called them with a string would need to be changed. I said in the first post I understood it was a breaking change :-)

    How many time have we heard
    Novice: This is stupid why are we still doing it
    Master: Compatibility, grasshopper.

    :-)

  12. ghost removed
    Needs-Triage
    on Jan 19, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-QuestionResolution-DuplicateWG-Engine-ParameterBinder

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions