更改 Powershell 会话的当前区域性,特定于 v3.0+

2023-12-26

我想更改当前交互式 Powershell 会话中接受的数据和错误的文化。我知道这个问题powershell:改变当前会话的文化 https://stackoverflow.com/questions/7052765/powershell-changing-the-culture-of-current-session以及这个问题的改变当前文化 https://superuser.com/questions/727459/changing-current-culture在超级用户上。主要问题是它不适用于 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            Русский (Россия)

UI 文化也不接受新设置。Set-Culture总的来说不起作用,无论我是否使用管理员访问权限 - 无论如何,它不应该受此影响,因为效果仅适用于单个进程。这Using-Culture https://stackoverflow.com/questions/2379514/powershell-formatting-values-in-another-culture/来自 MSDN Powershell 博客,由 SO 社区改编,可以工作,但只能部分工作,例如,对于当前的“ru-RU”文化,我能够从“6/19/15 2:26:02 PM”字符串中获取正确的日期,这是在“en-US”文化中通过Using-Culture "en-US" {get-date -date "6/19/15 2:26:02 PM"},但不可能收到另一种语言的错误:比如说Using-Culture "en-US" {$null.test='1'}导致俄语区域设置错误,就好像文化没有改变一样。

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

那么,在 PS3 及更高版本上是否仍然可以更改 Powershell 会话的文化?如果可以,如何更改? (或者又是bug,或者是PS3中我不知道的改变?)


更改文化仅影响线程并且仅适用于该进程。 您的 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

或者,在 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

效果很好。

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

更改 Powershell 会话的当前区域性,特定于 v3.0+ 的相关文章

随机推荐