0

问题

在具有文化的 Windows 会话中运行时,是否可以强制 PowerShell 以法语格式导出为 CSV en-GB

更多信息

我希望使用法语文化规则将一些数据导出到 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
4

1 回答 1

0

解决方法 #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:覆盖当前文化以匹配目标文化

另一种选择是更改当前文化的设置,使其共享所需文化的设置。这感觉更hacky;尽管根据情况可能会比上述更清洁/更实用。

例如,要使用 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/27/quick-hits-writing-to-a-read-only-property/ )... 但这已经让人觉得很讨厌了;所以我不会去那里,因为上面的内容足以满足我的需要。

于 2016-11-29T16:41:43.617 回答