转换为 CSV -使用文化忽略当前线程的区域性



问题

在使用en-GB文化的Windows会话中运行时,是否有可能强迫Powershell以法语格式导出到CSV?

更多信息

我希望使用法国文化规则将一些数据导出到CSV(即CSV的定界符设置为半隆,但也使用使用逗号的数字用于十进制位置,以及其他文化格式的差异;因此,仅使用-Delimiter参数不是足够)。

我提出了以下代码(基于https://stackoverflow.com/a/7052955/361842)

function Set-Culture
{
    [CmdletBinding(DefaultParameterSetName='ByCode')]
    param (
        [Parameter(Mandatory,ParameterSetName='ByCode',Position=1)]
        [string] $CultureCode
        ,
        [Parameter(Mandatory,ParameterSetName='ByCulture',Position=1)]
        [System.Globalization.CultureInfo] $Culture
    )
    begin {
        [System.Globalization.CultureInfo] $Culture = [System.Globalization.CultureInfo]::GetCultureInfo($CultureCode) 
    }
    process {
        [System.Threading.Thread]::CurrentThread.CurrentUICulture = $Culture
        [System.Threading.Thread]::CurrentThread.CurrentCulture = $Culture
    }
}
function Invoke-CommandInCulture {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory,ParameterSetName='ByCode',Position=1)]
        [string]$CultureCode
        ,
        [Parameter(Mandatory,Position=2)]
        [ScriptBlock]$Code
    )
    process {
        $OriginalCulture = Get-Culture
        try 
        {
            Set-Culture $CultureCode
            Write-Verbose (Get-Culture) #this always returns en-GB
            Invoke-Command -ScriptBlock $Code
        }
        finally 
        {
            Set-Culture $OriginalCulture
        }
    }
}

以下代码意味着此方法有效:

Invoke-CommandInCulture -CultureCode 'fr' -Code {
    [System.Threading.Thread]::CurrentThread.CurrentUICulture
    [System.Threading.Thread]::CurrentThread.CurrentCulture
} #shows that the command's thread's culture is French
Invoke-CommandInCulture -CultureCode 'fr' -Code {
    get-date
} #returns the current date in French 

但是,PowerShell对正在发生的事情有自己的想法

Invoke-CommandInCulture -CultureCode 'fr' -Code {
    get-culture
    "PSCulture: $PSCulture"
    "PSUICulture: $PSUICulture"        
} #returns my default (en-GB) culture; not the thread's culture

这会影响转换为CSV的逻辑:

Invoke-CommandInCulture -CultureCode 'fr' -Code {
    get-process | ConvertTo-CSV -UseCulture
} #again, uses my default culture's formatting rules; not the FR ones

orararound#1:自定义函数将值转换为给定文化中的字符串

这是解决方案;使用给定文化将每个字段转换为字符串,然后将字符串值转换为CSV:

function ConvertTo-SpecifiedCulture {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory,ValueFromPipeline)]
        [PSObject]$InputObject
        ,
        [Parameter(Mandatory)]
        [string]$CultureCode
        ,
        [Parameter(ParameterSetName='DefaultParameter', Position=0)]
        [System.Object[]]$Property
    )
    begin {
        [System.Globalization.CultureInfo] $Culture = [System.Globalization.CultureInfo]::GetCultureInfo($CultureCode) 
    }
    process {
        if($Property -eq $null) {$Property = $InputObject.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames}
        $Result = new-object -TypeName PSObject -Property @{}
        $Property | %{
            $Result | Add-Member -MemberType NoteProperty -Name $_ -Value ($InputObject."$_").ToString($Culture) 
        }
        $Result 
    }
}
Get-Process | select -first 2 | ConvertTo-SpecifiedCulture -CultureCode 'fr' | ConvertTo-CSV -Delimiter ';'

解决方案#2:覆盖当前文化以匹配目标文化

另一种选择是改变当前文化的设置,以便它共享所需文化的文化。这感觉更加刺耳。尽管取决于方案可能会比上述更清洁/更实用。

例如。要使用FR的数字格式,我们只是更新当前文化的数字格式以匹配FR的:

$(Get-Culture).NumberFormat = ([System.Globalization.CultureInfo]'FR').NumberFormat

...我们也可以为剩余(可设置的)属性做同样的事情:

function Set-CurrentCulture {
    [CmdletBinding()]
    param (
        [string]$CultureCode
    )
    begin {
        $Global:FakedCurrentCulture = $CultureCode #in case we need a reference to the current culture's name
        [System.Globalization.CultureInfo]$NewCulture = [System.Globalization.CultureInfo]::GetCultureInfo($CultureCode)
        [System.Globalization.CultureInfo]$ReferenceToCurrentCulture = Get-Culture
        Write-Verbose "Switching Defintion to $($NewCulture.Name)"
    }
    process {
        #NB: At time of writing, the only settable properties are NumberFormatInfo & DateTimeFormatInfo
        $ReferenceToCurrentCulture.psobject.properties | ?{$_.isSettable} | %{
            $propertyName = $_.Name
            write-verbose "Setting property $propertyName"
            write-verbose "- from: $($ReferenceToCurrentCulture."$propertyName")"
            write-verbose "- to: $($NewCulture."$propertyName")"
            $ReferenceToCurrentCulture."$propertyName" = $NewCulture."$propertyName"
        }
        #ListSeparator
        $ReferenceToCurrentCulture.TextInfo.psobject.properties | ?{$_.isSettable} | %{
            $propertyName = $_.Name
            write-verbose "Setting property TextInfo.$propertyName"
            write-verbose "- from: $($ReferenceToCurrentCulture.TextInfo."$propertyName")"
            write-verbose "- to: $($NewCulture.TextInfo."$propertyName")"
            $ReferenceToCurrentCulture.TextInfo."$propertyName" = $NewCulture."$propertyName"
        }
        #for some reason this errors
        #Localized, TwoDigitYearMax
        <#
        $ReferenceToCurrentCulture.Calendar.psobject.properties | ?{$_.isSettable} | %{
            $propertyName = $_.Name
            write-verbose "Setting property Calendar.$propertyName"
            write-verbose "- from: $($ReferenceToCurrentCulture.Calendar."$propertyName")"
            write-verbose "- to: $($NewCulture.Calendar."$propertyName")"
            $ReferenceToCurrentCulture.Calendar."$propertyName" = $NewCulture."$propertyName"
        }
        #>
    }
}
function Reset-CurrentCulture {
    [CmdletBinding()]
    param ()
    process {
        Set-CurrentCulture -CultureCode ((get-culture).Name)
    }
}
function Test-It {
    [CmdletBinding()]
    param ()
    begin {
        write-verbose "Current Culture: $Global:FakedCurrentCulture" 
    }
    process {
         1..5 | %{
            New-Object -TypeName PSObject -Property @{
                Integer = $_
                String = "Hello $_"
                Numeric = 2.139 * $_
                Money = (2.139 * $_).ToString('c')
                Date = (Get-Date).AddDays($_)
            }
         } | ConvertTo-Csv -NoTypeInformation
    }
}

Set-CurrentCulture 'fr' -Verbose
Test-It
Set-CurrentCulture 'en-GB' -Verbose
Test-It
Set-CurrentCulture 'en-US' -Verbose
Test-It
Set-CurrentCulture 'ar-DZ' -Verbose
Test-It
Reset-CurrentCulture -Verbose
Test-It

我们可能会走得更远,看看覆盖只读属性(这是可能的:https://learn-powershell.net/2016/06/06/27/quick-hits-hits-writing-writing-to-a-a-read-read-only-property/)...但是这已经非常讨厌;因此,我不会去那里,因为上述时间足以满足我的需求。

最新更新