更改 Powershell 会话的当前文化,特定于 v3.0+

Ves*_*per 5 powershell culture powershell-3.0 powershell-4.0

我想改变当前交互式 Powershell 会话中接受的数据和错误的文化。我知道这个问题powershell:改变当前会话的文化和这个问题改变SuperUser 上的当前文化。主要问题是它不适用于 Powershell 3.0 和 4.0。

PS C:\users\me\Documents> [system.threading.thread]::currentthread.currentculture

LCID             Name             DisplayName
----             ----             -----------
1049             ru-RU            ??????? (??????)


PS C:\users\me\Documents> [system.threading.thread]::currentthread.currentculture=[system.globalization.cultureinfo]"en-US"
PS C:\users\me\Documents> [system.threading.thread]::currentthread.currentculture

LCID             Name             DisplayName
----             ----             -----------
1049             ru-RU            ??????? (??????)
Run Code Online (Sandbox Code Playgroud)

UI 文化也不接受新设置。Set-Culture无论我是否使用管理员访问权限,总的来说都不起作用 - 无论如何,它不应受此影响,因为效果仅适用于单个进程。在Using-Culture从MSDN博客Powershell的,适于通过SO社会的作品,但只是部分,例如,以“RU-RU”当前文化我能够从“15年6月19日下午2时26分02秒”获得合适的日期字符串,它通过 位于“en-US”区域性中Using-Culture "en-US" {get-date -date "6/19/15 2:26:02 PM"},但不可能收到另一种语言的错误:sayUsing-Culture "en-US" {$null.test='1'}导致俄语区域设置错误,就好像区域性没有改变一样。

此行为已在我安装了 Powershell 4.0 的本地 Win7 Professional 工作站和安装了 Powershell 3.0 的 Windows Server 2012 上进行了测试,这是解析错误本地化日期字符串所必需的。后者具有“en-US”的 UI 文化和系统区域设置“ru-RU”。

那么,PS3 及更高版本是否仍然可以改变 Powershell 会话的文化,如果是,如何改变?(或者是再次出现错误,还是我不知道的 PS3 更改?)

Sce*_*ist 3

更改文化仅影响线程并且仅适用于该进程。您的 PS 窗口是在当前区域设置下启动的,因此线程具有该区域设置。在当前系统区域设置下启动的 PS 窗口中键入“[System.Threading.Thread]::CurrentThread.CurrentCulture”,将始终显示该区域设置。

如果你在 ISE 中运行它,它应该解释很少:

 function Set-Culture([System.Globalization.CultureInfo] $culture) {
[System.Threading.Thread]::CurrentThread.CurrentUICulture = $culture
[System.Threading.Thread]::CurrentThread.CurrentCulture = $culture }

Set-Culture en-US
[system.threading.thread]::currentthread.currentculture
Pause
Run Code Online (Sandbox Code Playgroud)

或者,在 PS 窗口中:

function Set-Culture([System.Globalization.CultureInfo] $culture) { [System.Threading.Thread]::CurrentThread.CurrentUICulture = $culture ; [System.Threading.Thread]::CurrentThread.CurrentCulture = $culture } ; Set-Culture en-US ; [system.threading.thread]::currentthread.currentculture
Run Code Online (Sandbox Code Playgroud)

效果很好。

如果您想要一个具有新文化的 PS 窗口,您需要使用该文化启动它,而不是事后尝试更改它。