title: NullReferenceException when grouping collection by arrays in powershell
body: <p>Very simple scenario: </p>
  
  <ul>
  <li>there's an array of logs parsed from the file</li>
  <li>each log has property <code>Exceptions</code> that is array of exceptions parsed from log body</li>
  </ul>
  
  <hr>
  
  <pre><code>$logs | Get-Member
  Name        MemberType Definition
  ----        ---------- ----------
  Equals      Method     bool Equals(System.Object obj)
  GetHashCode Method     int GetHashCode()
  GetType     Method     type GetType()
  ToString    Method     string ToString()
  Content     Property   string Content {get;set;}
  Exceptions  Property   string[] Exceptions {get;set;}
  Line        Property   int Line {get;set;}
  Source      Property   string Source {get;set;}
  Time        Property   System.Nullable[datetime] Time {get;set;}
  </code></pre>
  
  <p>Unit tests on parser confirm that <code>Exceptions</code> is never null.
  Also:</p>
  
  <pre><code>$logs | where {$_.Exceptions -eq $null} | measure
  
  Count    : 0
  Average  : 
  Sum      : 
  Maximum  : 
  Minimum  : 
  Property :
  </code></pre>
  
  <p>But: </p>
  
  <pre><code>$logs | group {$_.Exceptions}
  group : Object reference not set to an instance of an object.
  At line:1 char:6
  + $l | group {$_.Exceptions}
  +      ~~~~~~~~~~~~~~~~~~~~~
  + CategoryInfo          : NotSpecified: (:) [Group-Object], NullReferenceException
  + FullyQualifiedErrorId : System.NullReferenceException,Microsoft.PowerShell.Commands.GroupObjectCommand
  </code></pre>
  
  <p>So considering that the check measuring number of elements with null Exceptions returned zero this should work exactly as the call above:</p>
  
  <pre><code>$logs | where Exceptions -ne $null | group {$_.Exceptions}
  </code></pre>
  
  <p>But this time it succeeds:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>The question is <strong>why it succeeds after I filter out all the elements with null <code>Exceptions</code> while measure-object suggests that there's nothing null in there</strong>?</p>
  
  <p>Solution for grouping my logs (good enough, because I don't need groups, just count of specific occurences) :</p>
  
  <pre><code>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"
  }
  </code></pre>