Skip to content

Compiled cmdlets - unlike functions - perform culture-sensitive type conversion during parameter binding #6989

@mklement0

Description

@mklement0

Note: Fixing this inconsistency is probably not an option so as not to break existing code.
If so, it should be documented.

PowerShell by design applies the invariant culture when converting from a string, which applies to both explicit conversions with casts and implicit ones during parameter binding in functions.

By contrast, a culture-sensitive conversion is performed during parameter binding for compiled cmdlets.

Steps to reproduce

# Create a cmdlet that accepts a [datetime] argument.
Add-Type @'
  using System;
  using System.Management.Automation;
  [Cmdlet("Get", "Foo_Cmdlet")]
  public class GetFooCmdlet : Cmdlet {

    [Parameter(Position=0)]
    public DateTime Date { get; set; }

    protected override void ProcessRecord() {
      WriteObject(Date);      
    }
  }
'@ -PassThru | % Assembly | Import-Module

# Define a seemingly equivalent function.
function Get-Foo_Func {
  param(
    [DateTime] $Date
  )
  process {
    $Date
  }
}

$prevCulture = [cultureinfo]::CurrentCulture
[cultureinfo]::CurrentCulture = 'de-DE'

# This German-format date string doesn't work with the invariant culture.
# E.g., [datetime] '19-06-2018' breaks.
$dateStr = '19-06-2018'

# Pass the string to a [datetime]-typed parameter to force implicit conversion.

# Function: INVARIANT CULTURE is applied -> breaks.
Get-Foo_Func $dateStr

# Cmdlet: CURRENT CULTURE is applied -> succeeds.
Get-Foo_Cmdlet $dateStr

[cultureinfo]::CurrentCulture = $prevCulture

Expected behavior

Both calls (Get-Foo_Func) and (Get-Foo_Cmdlet) should fail with:

Get-Foo_Func : Cannot process argument transformation on parameter 'Date'. Cannot convert value "19-06-2018" to type "System.DateTime". Error: "String was not recognized as a valid DateTime."

Actual behavior

Get-Foo_Func fails, and Get-Foo_Cmdlet succeeds:

Get-Foo_Func : Cannot process argument transformation on parameter 'Date'. Cannot convert value "19-06-2018" to type "System.DateTime". Error: "String was not recognized as a valid DateTime."
#...

Dienstag, 19. Juni 2018 00:00:00

Environment data

PowerShell Core v6.0.2 on macOS 10.13.4
PowerShell Core v6.0.2 on Ubuntu 16.04.4 LTS
PowerShell Core v6.0.2 on Microsoft Windows 10 Pro (64-bit; Version 1709, OS Build: 16299.371)
Windows PowerShell v5.1.16299.251 on Microsoft Windows 10 Pro (64-bit; Version 1709, OS Build: 16299.371)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-Discussionthe issue may not have a clear classification yet. The issue may generate an RFC or may be reclassifResolution-DuplicateThe issue is a duplicate.WG-Enginecore PowerShell engine, interpreter, and runtime

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions