PowerShell类方法返回psCustomObject报错及返回类型性能对比问题
PowerShell 复杂返回类型性能测试与psCustomObject类方法返回报错
初始测试代码
class pxObject { [String]$String [String]$Failure [String]$Error pxObject ([String]$string, [String]$failure, [String]$error) { $this.String = $string $this.Failure = $failure $this.Error = $error } } class pxReturn { static [HashTable] Hash ([String]$string, [String]$failure, [String]$error) { [HashTable]$returnHash = @{ String = $string Failure = $failure Error = $error } return $returnHash } static [psCustomObject] psObject ([String]$string, [String]$failure, [String]$error) { [psCustomObject]$returnObject = [psCustomObject]@{ String = $string Failure = $failure Error = $error } return $returnObject } static [pxObject] pxObject ([String]$string, [String]$failure, [String]$error) { [pxObject]$returnObject = [pxObject]::new($string, $failure, $error) return $returnObject } } [Int]$count = 1000 CLS Write-Host 'Hash ' -NoNewLine (Measure-Command { foreach ($i in 1..$count) { [pxReturn]::Hash("String $i", "Failure $i", "Error $i") } }).TotalSeconds Write-Host 'psObject ' -NoNewLine (Measure-Command { foreach ($i in 1..$count) { [pxReturn]::psObject("String $i", "Failure $i", "Error $i") } }).TotalSeconds Write-Host 'pxObject ' -NoNewLine (Measure-Command { foreach ($i in 1..$count) { [pxReturn]::pxObject("String $i", "Failure $i", "Error $i") } }).TotalSeconds
运行时异常现象
- 针对类内
psObject方法的测试项,被Measure-Command包裹运行时,抛出The given key was not present in the dictionary错误。 - 考虑到
Measure-Command的代码块可能遮蔽真实错误来源,注释掉外层Measure-Command直接调用[pxReturn]::psObject方法时,会抛出无行号定位信息的An error occurred while creating the pipeline错误。 - 此前已验证:完全相同的psCustomObject实例化逻辑放在普通函数中可正常运行,因此补充了函数版对照测试。
对照验证设计
普通函数版psCustomObject返回逻辑代码:
function psObjectReturn ([String]$string, [String]$failure, [String]$error) { [psCustomObject]$returnObject = [psCustomObject]@{ String = $string Failure = $failure Error = $error } return $returnObject }
配套的函数版性能测试代码:
Write-Host 'psObject (function) ' -NoNewLine (Measure-Command { foreach ($i in 1..$count) { $test = psObjectReturn "String $i" "Failure $i" "Error $i" } }).TotalSeconds
该对照测试可正常运行,无任何报错。
已测得的性能数据
Hash 0.01107 psObject (function) 0.0453963 pxObject 0.0245367
从结果可观测的性能排序为:哈希表返回 > 自定义类实例返回 > 普通函数返回psCustomObject。
核心待解答问题
- 是否存在PowerShell类方法无法将psCustomObject作为合法返回类型的硬性限制
- 类方法调用触发无明确定位报错的底层原因
内容的提问来源于stack exchange,提问作者Gordon
相关产品推荐
相关产品推荐

