在powershell中按数组对集合进行分组时出现NullReferenceException

在powershell中按数组对集合进行分组时出现NullReferenceException,powershell,exception,grouping,Powershell,Exception,Grouping,非常简单的场景: 有一个从文件中解析的日志数组 每个日志都有属性Exceptions,该属性是从日志体解析的异常数组 解析器上的单元测试确认异常从不为空。 此外: 但是: 因此,考虑到带有null异常的元素的check-measurement数量返回零,这应该与上面的调用完全相同: $logs | where Exceptions -ne $null | group {$_.Exceptions} 但这次它成功了: Values : {SecurityException} Count

非常简单的场景:

  • 有一个从文件中解析的日志数组
  • 每个日志都有属性
    Exceptions
    ,该属性是从日志体解析的异常数组

解析器上的单元测试确认
异常
从不为空。 此外:

但是:

因此,考虑到带有null异常的元素的check-measurement数量返回零,这应该与上面的调用完全相同:

$logs | where Exceptions -ne $null | group {$_.Exceptions}
但这次它成功了:

Values : {SecurityException}
Count  : 28
Group  : {ErrorLog, ErrorLog, ErrorLog, ErrorLog...}
Name   : SecurityException 

Values : {ValidationException}
Count  : 707
Group  : {ErrorLog, ErrorLog, ErrorLog, ErrorLog...}
Name   : ValidationException

Values : {SoapException ValidationException}
Count  : 6
Group  : {ErrorLog, ErrorLog, ErrorLog, ErrorLog...}
Name   : SoapException ValidationException
问题是为什么在我过滤掉所有包含null
异常的元素后它会成功
,而度量对象表明其中没有null

对我的日志进行分组的解决方案(足够好了,因为我不需要分组,只需计算具体发生的次数):


请注意,Exceptions属性是一个字符串数组。所有比较运算符都用作标量(单个项)和数组运算符。当对标量使用时,它返回布尔值($true/$false)。对数组使用时,它返回与条件匹配的数组的所有成员

$logs | where {$_.Exceptions -eq $null} | measure

返回0项,因为$$.Exceptions数组中没有空字符串。

这已经很重要了,谢谢:)我实际运行了这个
$logs |其中{$.Exceptions.Count-eq 0}| measure
,并发现结果正好是没有异常的日志数。所以我相信,当我在数组上调用
Group Object
时,它会比较数组中的字符串,在这里null不是令人满意的,或者作为创建组的键。是否有某种方法可以强制
组对象
处理空数组而不丢弃它们或添加空字符串?
$logs | where Exceptions -ne $null | group {$_.Exceptions}
Values : {SecurityException}
Count  : 28
Group  : {ErrorLog, ErrorLog, ErrorLog, ErrorLog...}
Name   : SecurityException 

Values : {ValidationException}
Count  : 707
Group  : {ErrorLog, ErrorLog, ErrorLog, ErrorLog...}
Name   : ValidationException

Values : {SoapException ValidationException}
Count  : 6
Group  : {ErrorLog, ErrorLog, ErrorLog, ErrorLog...}
Name   : SoapException ValidationException
function Group-Logs([Log[]]$logs)
{
    $logs | where {$_.Exceptions.Count -gt 0} | group {$_.Exceptions} -NoElement | sort Count

    $noExceptionsLogsNumber = ($logs | where {$_.Exceptions.Count -eq 0}).Count
    Write-Host "Logs with no exceptions found: $noExceptionsLogsNumber"
}
$logs | where {$_.Exceptions -eq $null} | measure