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

使用Using Module时模块触发索引越界错误的问题排查

问题:Using Module加载含Import-LocalizedData的模块时触发索引越界错误

初始实现与正常运行结果

我创建了简单模块testUsingModule.psm1及其对应的psd1文件:

$Messages = @{    
    # fallback messages
    foo = '<default fallback>'
}

write-host -fore green $Messages.foo

class xClass {    
    [string]$foo

    xClass() {
        $this.foo = $script:messages.foo
    }

    xClass([string]$foo) {
        $this.foo = $foo
    }
}

随后在脚本testUsingModule.ps1中调用该模块:

Using Module testUsingModule

$x = [xClass]::new()
write-host $x.foo

$x = [xClass]::new('bar')
write-host $x.foo

运行后得到预期结果:

powershell -noprofile -command V:\testUsingModule.ps1
<default fallback>
<default fallback>
bar

添加本地化逻辑后的异常问题

当在模块中添加本地化消息导入逻辑后:

$Messages = @{    

    # fallback messages
    foo = '<default fallback>'
}

Import-LocalizedData -BindingVariable 'Messages' -Filename testUsingModule-msg -ErrorAction SilentlyContinue

write-host -fore green $Messages.foo

[...]

若对应语言包不可用,会触发索引越界错误:

powershell -noprofile -command V:\testUsingModule.ps1

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
At line:1 char:1

  • V:\testUsingModule.Ps1
  • CategoryInfo : OperationStopped: (:) [], ArgumentOutOfRangeException
  • FullyQualifiedErrorId : System.ArgumentOutOfRangeException

我尝试用try{}catch{}包裹Import-LocalizedData,无论设置ErrorAction为SilentlyContinue还是Stop,均会触发相同错误;但使用Import-Module加载模块则无此问题。这是我忽略了细节,还是Using Module的未文档化特性?

附PowerShell版本信息:

Name                           Value
----                           -----
PSVersion                      5.1.19041.6926
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.19041.6926
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.11 10:22:16