调用返回Null的PowerShell静态函数触发索引越界异常求助
PowerShell 5.1静态函数返回空相关对象引发索引越界异常问题
异常现象
在Windows 7系统的PowerShell 5.1环境中,调用返回空相关对象的静态函数时,触发如下索引越界异常:
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index At H:\test\issue_nullret.ps1:12 char:5 + [CmdUtils]::RunCommand($cmd) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (:) [], ArgumentOutOfRangeExce ption + FullyQualifiedErrorId : System.ArgumentOutOfRangeException
复现脚本
class CmdUtils { static [object]RunCommand($cmd) { $res = .$cmd #### if ($res -eq $null) { $res = $null } ### uncommenting this fixes it, but why ?? return $res } } function RunCmd($cmd) { [CmdUtils]::RunCommand($cmd) ### this errors out at the [ ] brackets } RunCmd {write-host 'Hi'}
问题原因
write-host的输出直接打印到控制台,不会进入管道,因此. $cmd执行后返回的不是$null,而是PowerShell内部的AutomationNull([System.Management.Automation.Internal.AutomationNull]::Value)——一种表示“无输出”的特殊空集合。- PowerShell 5.1在处理静态方法返回AutomationNull时存在bug:内部逻辑错误地将其视为普通集合,并尝试访问索引位置的元素,空集合没有可访问的索引,因此触发
ArgumentOutOfRangeException。
修复代码的作用
取消注释if ($res -eq $null) { $res = $null }后,代码将AutomationNull显式转换为真正的$null值。PowerShell处理静态方法返回$null时,不会触发上述索引访问的错误逻辑,因此异常消失。
PowerShell 7.4中的表现
该bug已在PowerShell 7系列中被修复,在7.4环境中执行上述脚本不会出现异常。PowerShell 7重构了返回值的处理逻辑,对AutomationNull的类型转换和返回流程做了优化,避免了这种内部错误。
内容的提问来源于stack exchange,提问作者yacc
相关产品推荐
相关产品推荐

