Skip to content

PowerShell use different logic, when converting passed value to parameter type, for compiled and script cmdlets #3348

Closed

Description

@PetSerAl

Steps to reproduce

PS> Add-Type -TypeDefinition @'
     using System;
     using System.Management.Automation;
     [Cmdlet("Test", "Compiled")]
     public class TestCompiled : PSCmdlet {
         [Parameter(Position = 0)]
         public DateTime DT;
         protected override void EndProcessing() {
             WriteObject(DT);
         }
     }
'@ -PassThru | Select-Object -First 1 -ExpandProperty Assembly | Import-Module
PS> function Test-Script {
     param(
         [DateTime]$DT
     )
     $DT
 }
PS> @(
     [CultureInfo]::CurrentCulture = 'ru-RU'
     Test-Compiled 1/11/1111
     Test-Script   1/11/1111
     [CultureInfo]::CurrentCulture = 'en-US'
 )

Wednesday, November 1, 1111 12:00:00 AM
Wednesday, January 11, 1111 12:00:00 AM

Expected behavior

Same dates in both cases.

Actual behavior

Strings get parsed with different culture in mind.

Environment data

> $PSVersionTable

Name                           Value
----                           -----
GitCommitId                    v6.0.0-alpha.17-18-gedecf7e04d65f7183cd1d278daa5ebed2970813f
PSRemotingProtocolVersion      2.3
PSEdition                      Core
WSManStackVersion              3.0
CLRVersion
BuildVersion                   3.0.0.0
PSVersion                      6.0.0-alpha
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0, 5.0, 5.1.10032.0, 6.0.0}
SerializationVersion           1.1.0.1

My thoughts about the problem

I think the problem happens due to PowerShell automatically adds ArgumentTypeConverterAttribute to typed parameters for script cmdlets:

PS> (Get-Command Test-Script).Parameters.DT.Attributes | % GetType | % FullName
System.Management.Automation.ParameterAttribute
System.Management.Automation.ArgumentTypeConverterAttribute

but not doing the same for compiled cmdlets:

PS> (Get-Command Test-Compiled).Parameters.DT.Attributes | % GetType | % FullName
System.Management.Automation.ParameterAttribute

That attribute make conversion use InvariantCulture, while compiled cmdlets use CurrentCulture for conversion.

Activity

  1. added
    WG-Engine
    Issue-Discussion
    on Mar 18, 2017
  2. iSazonov commented on Oct 8, 2017

    @iSazonov
    Collaborator

    Steve Lee (@SteveL-MSFT) I think we should fix this before RTM.

  3. added this to the milestone on Oct 8, 2017
  4. daxian-dbw commented on Oct 13, 2017

    @daxian-dbw
    Member

    PetSerAl Thanks for the analysis!
    ArgumentTypeConverterAttribute uses InvariantCulture when calling LanguagePrimitives.ConvertTo, while ParameterBinderBase.CoerceTypeAsNeeded uses CurrentCulture when calling LanguagePrimitives.ConvertTo.

    I will submit a PR to change ArgumentTypeConverterAttribute to use CurrentCulture as well.

  5. PetSerAl commented on Oct 13, 2017

    @PetSerAl
    ContributorAuthor

    Dongbo Wang (@daxian-dbw)

    I will submit a PR to change ArgumentTypeConverterAttribute to use CurrentCulture as well.

    Should it be other way around? Since PowerShell explicit cast use InvariantCulture:

    @(
         [CultureInfo]::CurrentCulture = 'ru-RU'
         [DateTime] '1/11/1111'
         [String] 1.1
         [CultureInfo]::CurrentCulture = 'en-US'
    )

    I would expect that implicit cast to parameter type should also use InvariantCulture.

  6. daxian-dbw commented on Oct 13, 2017

    @daxian-dbw
    Member

    PetSerAl That's a good point. I will change ParameterBinderBase.CoerceTypeAsNeeded to use InvariantCulture.

  7. iSazonov commented on Oct 13, 2017

    @iSazonov
    Collaborator

    It seems strange that PowerShell ignores Culture.
    We need more discussion - it is breaking change.

  8. added
    Breaking-Change
    on Oct 13, 2017
  9. daxian-dbw commented on Oct 13, 2017

    @daxian-dbw
    Member

    Ilya (@iSazonov) I guess it's for the scripts to be more portable. I added the breaking change label.

  10. iSazonov commented on Oct 13, 2017

    @iSazonov
    Collaborator

    I think it is not documented. We need good description for this "portability" with InvariantCulture in argument convertion and parameter binding. Otherwise we'll have a big misunderstanding and many negative feedbacks.
    Also we need @powershell-committee approvement for a breaking change.
    Both my comment is for your PR.

  11. added
    Review - Committee
    on Oct 13, 2017
  12. added
    Resolution-Won't Fix
    on Oct 19, 2017
  13. daxian-dbw commented on Oct 19, 2017

    @daxian-dbw
    Member

    @PowerShell/powershell-committee has rejected the PR #5106. Quote the decision here:

    @PowerShell/powershell-committee reviewed this and due to the potential for breaking many existing modules, it's too risky to make this change so that c# and script cmdlets are alike for this case. We should keep the current behavior.

    I will close this issue as 'Won't Fix'.

  14. added
    Committee-Reviewed
    and removed
    Review - Committee
    on Oct 19, 2017
  15. iSazonov commented on Oct 19, 2017

    @iSazonov
    Collaborator

    Does anyone know how many (module) breaking changes we've already made? It seems so much that talking about these changes is no longer relevant.
    Also if we already is InvariantCulture for arguments and casting in scripts where is entry points where customers can catch problems?

  16. daxian-dbw commented on Oct 20, 2017

    @daxian-dbw
    Member

    Ilya (@iSazonov) One example I got from the committee was the C# modules running on, for example, Japanese machines. After this change, it may happen that some cmdlets are broken with the same input arguments because the conversion has changed.
    But I do agree with you that this inconsistency is unpleasant 🤕

  17. iSazonov commented on Oct 20, 2017

    @iSazonov
    Collaborator

    I have another example - EMS (Microsoft Exchange server Management Shell).
    If you is not on English culture session it's always a huge mystery for you to make a search request! The situation is even worse if you try to make such a request dynamically in a script. In essence, you cannot create a script that you can trust. 😞

    I think we should consider this Issue more closely.

  18. daxian-dbw commented on Oct 20, 2017

    @daxian-dbw
    Member

    Interesting, I presume the EMS example is where the current CurrentCulture conversion behavior causes a usability issue, right? So in this case, it's preferable to have InvariantCulture conversion so that things can work on non-english culture environment?

  19. lzybkr commented on Oct 20, 2017

    @lzybkr
    Contributor

    Proxies certainly make this issue more complicated - something may work when calling the cmdlet, but a proxy is introduced (e.g. for RBAC) and now it doesn't.

  20. jhoneill commented on Jan 19, 2022

    @jhoneill

    To unify some of the stuff which I raised in #16767.

    With non-US, culture selected get-date "9/1/2022" returns "09 January 2022 00:00:00" which is what most users would expect and therefore good. If the culture is US it returns "Thursday, September 1, 2022 12:00:00 AM", still what users would expect However using Get-Date makes a non-portable script because the output for a given input isn't consistent, and therefore bad.

    CASTING with [datetime]$x or [string]$x or [double]$x always uses invariant culture.
    If you are on EN-US [string][datetime]::now shows the time using 24 hour clock where the EN-US locale uses 12 hour with "AM/PM" If you are in France and use "," instead of "." for your decimal point [double]"123,45" might give an unexpected result because it uses invariant.
    [Convert], .Tostring() and Parse() use local (or specified) culture. Using these in a script with "whatever the local culture happens to be" can also produce non portable scripts. If numbers will be in French format, it is better to state French culture explicitly than assume the script will only ever run with culture set to French.

    Staying with French we can see that the -AS operator sometimes supports local culture and sometimes invariant.

    > [datetime]::parse("19 janvier 2022")
    mercredi 19 janvier 2022 00:00:00
    
    > "19 janvier 2022" -as [datetime]
    mercredi 19 janvier 2022 00:00:00
    
    >  [double]::parse("1 234 567,89")
    1234567,89
    
    >  "1 234 567,89" -as [double]     # Local with spaces does not parse and the result is null
    > $null -eq ("1 234 567,89" -as [double])
    True
    
    > "1,234,567.89" -as [double]  # Invariant format does parse and the result is displayed in local format
    1234567,89
    

    Compiled cmdlet parameters seem to follow -AS so with French selected Get-Date "19 janvier 2022" understands that "janvier" is the first month of the year in this culture but Select -first "1 000" fails because a space is not accepted as a separator. Select -first "1,000" works . As a side note, [int]::parse() won't process either form

    I'm not sure how -AS links to CorceTypeAsNeeded in what Dongbo Wang (@daxian-dbw) said above :

    ArgumentTypeConverterAttribute uses InvariantCulture when calling LanguagePrimitives.ConvertTo, while ParameterBinderBase.CoerceTypeAsNeeded uses CurrentCulture when calling LanguagePrimitives.ConvertTo.

    When we write param ( [datetime]$d, ) it looks like a cast, although it is really adding an ArgumentTypeConverterAttribute that will do a cast. If would be odd if the result were not the same as

    param (  $d, ) 
    $d = [datetime]$d
    

    It could have been created to do the same as

    param (  $d, ) 
    $d =  $d -as [datetime]
    

    but people wouldn't expect this version.

    This is the solution for the proxy-function case, not to specify a type in the param block and to the use convert inside the function.

    The inconsistency of -As and the different handling of date time parameters in different kinds of commands is annoying, but the problems that would result from making everything consistent are far greater. It is worth ensuring that help for datetime parameters says whether they accept local format or require invariant.

  21. iSazonov commented on Jan 19, 2022

    @iSazonov
    Collaborator

    Staying with French we can see that the -AS operator sometimes supports local culture and sometimes invariant.

    I think the operator uses the same code path in both cases. So I guess it could be PowerShell parser issue. /cc Rain Sallow (/u/ta11ow) (@vexx32)

  22. vexx32 commented on Jan 19, 2022

    @vexx32
    Collaborator

    Don't think it's necessarily a parsing issue, but it could be a compiler issue. Patrick Meinecke (@SeeminglyScience) might have more insight here.

  23. SeeminglyScience commented on Jan 19, 2022

    @SeeminglyScience
    Contributor

    Nah it's a compiler issue. Also I think James O'Neill (@jhoneill) meant to link #16593 which goes into it in more detail.

  24. jhoneill commented on Jan 19, 2022

    @jhoneill

    Staying with French we can see that the -AS operator sometimes supports local culture and sometimes invariant.

    I think the operator uses the same code path in both cases. So I guess it could be PowerShell parser issue. /cc Rain Sallow (/u/ta11ow) (@vexx32)

    -AS [datetime] uses local culture

    -As [double] -As [int32] use invariant

  25. jhoneill commented on Jan 19, 2022

    @jhoneill

    I set the culture to French. You can see that a double displays with "," as a decimal separator, and the date uses French names.

    .ToString() always uses the local culture
    [string] always uses invariant
    -As [string] converts numbers with invariant, and dates with local.

    > [math]::pi
    3,14159265358979
    > [datetime]::now
    
    mercredi 19 janvier 2022 18:33:38
    
    
    ps > [datetime]::now.ToString()
    19/01/2022 18:39:04
    
    ps > [math]::pi.ToString()
    3,141592653589793
    
    
    ps > [string][math]::pi
    3.14159265358979
    
    ps > [string][datetime]::now
    01/19/2022 18:42:33
    
    ps > [datetime]::now -as [string]
    19/01/2022 18:34:21
    
    ps >  [math]::pi -as [string]
    3.14159265358979
    
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Breaking-ChangeCommittee-ReviewedIssue-DiscussionResolution-Won't FixWG-Engine

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions