You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PowerShell中检查custom culture(自定义区域性)是否存在

问题根因

[cultureinfo]::GetCultureInfo() 方法在传入未注册的区域性名称时,会直接抛出 CultureNotFoundException 异常,不会返回null值,因此你原有的非空判断逻辑无法生效,程序会在区域性未注册时直接崩溃。

修正后的完整代码
$cultureName = 'gh-es'
$customCulture = $null

try {
    # 尝试获取自定义区域性,不存在会抛出对应异常
    $customCulture = [cultureinfo]::GetCultureInfo($cultureName)
}
catch [System.Globalization.CultureNotFoundException] {
    # 捕获到指定异常即说明区域性未注册,无需额外处理,继续走注册逻辑即可
}

if ($customCulture -ne $null) {
    Write-Output "culture already registered"
}
else {
    $BaseCulture = [cultureinfo]::GetCultureInfo('es-US') 
    $BaseRegion = New-Object System.Globalization.RegionInfo 'es-US' 
    try {
        # 加载程序集并注册自定义区域性
        Add-Type -AssemblyName sysglobl
        $CultureBuilder = New-Object System.Globalization.CultureAndRegionInfoBuilder @($cultureName,[System.Globalization.CultureAndRegionModifiers]::None)
        $CultureBuilder.LoadDataFromCultureInfo($BaseCulture)
        $CultureBuilder.LoadDataFromRegionInfo($BaseRegion)
        $CultureBuilder.Register()
        Write-Output "custom culture $cultureName registered successfully"
    }
    catch {
        throw
    }
}
注意事项
  • 注册自定义区域性需要管理员权限,否则执行Register()方法时会抛出权限不足的异常
  • 已注册的自定义区域性会持久化保存在系统中,除非手动调用Unregister()方法删除,否则重启程序也不需要重复注册

内容的提问来源于stack exchange,提问作者Shian JA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 23:21:03