title: How to write a PowerShell advanced function that can work with both piped in objects and objects get from parameter value?
body: <p>I'm writing a function <code>Chunk-Object</code> that can <em>chunk</em> an array of objects into sub arrays. For example, if I pass it an array <code>@(1, 2, 3, 4, 5)</code> and specify <code>2</code> elements per chunk, then it will return 3 arrays <code>@(1, 2)</code>, <code>@(3, 4)</code> and <code>@(5)</code>. Also the user can provide an optional <code>scriptblock</code> parameter if they want to process each elements before chunk them into sub arrays. Now my code is:</p>
  
  <pre><code>function Chunk-Object()
  {
      [CmdletBinding()]
      Param(
          [Parameter(Mandatory = $true,
                     ValueFromPipeline = $true,
                     ValueFromPipelineByPropertyName = $true)] [object[]] $InputObject,
          [Parameter()] [scriptblock] $Process,
          [Parameter()] [int] $ElementsPerChunk
      )
  
      Begin {
          $cache = @();
          $index = 0;
      }
  
      Process {
          foreach($o in $InputObject) {
              $current_element = $o;
              if($Process) {
                  $current_element = &amp; $Process $current_element;
              }
              if($cache.Length -eq $ElementsPerChunk) {
                  ,$cache;
                  $cache = @($current_element);
                  $index = 1;
              }
              else {
                  $cache += $current_element;
                  $index++;
              }
          }
      }
  
      End {
          if($cache) {
              ,$cache;
          }
      }
  }
  
  
  (Chunk-Object -InputObject (echo 1 2 3 4 5 6 7) -Process {$_ + 100} -ElementsPerChunk 3)
  Write-Host "------------------------------------------------"
  (echo 1 2 3 4 5 6 7 | Chunk-Object -Process {$_ + 100} -ElementsPerChunk 3)
  </code></pre>
  
  <p>The result is:</p>
  
  <pre><code>PS C:\Users\a&gt; C:\Untitled5.ps1
  100
  100
  100
  100
  100
  100
  100
  ------------------------------------------------
  101
  102
  103
  104
  105
  106
  107
  
  PS C:\Users\a&gt; 
  </code></pre>
  
  <p>As you can see, it works with piped in objects, but does not work with values get from parameter. How to modify the code to make it work in both cases?</p>