title: PowerShell Where-Object vs. Where method
body: <p>An interesting and weird thing I noticed writing PowerShell classes lines:</p>
  
  <pre><code>class A {
  
      [object] WhereObject(){
          return @(1,2) | Where-Object {$_ -gt 2}
      }
  
      [object] Where(){
          return @(1,2).Where( {$_ -gt 2})
      }
  }
  
  $a = new-object A
  $a.WhereObject() # Throw exception Index was out of range. Must be non-negative and less than the size of the collection.
  
  $a.Where() # Works well
  </code></pre>
  
  <p>It looks like it is by design. Why does it work so?</p>
  
  <p><strong>Workaround</strong></p>
  
  <p>Function which explicitly convert "empty" value to $null:</p>
  
  <pre><code>function Get-NullIfEmpty {
     param(
         [Parameter(ValueFromPipeline=$true)][array] $CollectionOrEmtpy
     )
  
     begin { $output = $null }
  
     process
     {
        if($output -eq $null -and $CollectionOrEmtpy -ne $null){
            $output = @()
        }
        foreach ($element in $CollectionOrEmtpy)
        {
            $output += $element
        }
     }
  
     end { return $output }
  }
  </code></pre>
  
  <p>In this case, the method will look like:</p>
  
  <pre><code>[object] WhereObject() {
     return @(1,2) | Where-Object {$_ -gt 2} | Get-NullIfEmpty
  }
  </code></pre>
  
  <p>I tried to return an empty array from the class method, but it is also tricky because for a regular function an empty array means "nothing" as well. If you have a call chain like method1 -> function -> method2 - method1 throw the same exception. Because the function converts an empty array to nothing.</p>
  
  <p>So converting to $null is optimal in my case :)</p>